You don't need to convert NumPy array to Mat because OpenCV cv2 module can accept NumPyarray. The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy array is equal to 255. So you should divide by 255 in your code, as shown below.

img = numpy.zeros([5,5,3])

img[:,:,0] = numpy.ones([5,5])*64/255.0
img[:,:,1] = numpy.ones([5,5])*128/255.0
img[:,:,2] = numpy.ones([5,5])*192/255.0

cv2.imwrite('color_img.jpg', img)
cv2.imshow("image", img)
cv2.waitKey()
Answer from bikz05 on Stack Overflow
🌐
Saturn Cloud
saturncloud.io › blog › converting-numpy-arrays-to-images-using-cv2-and-pil
Converting Numpy Arrays to Images using CV2 and PIL | Saturn Cloud Blog
May 1, 2026 - Finally, we use cv2.imwrite() to save the array as an image. The Python Imaging Library (PIL) is another powerful library for opening, manipulating, and saving many different image file formats. To convert a Numpy array to an image with PIL, we use the Image.fromarray() function...
Discussions

How can I turn numpy ndarray into an opencv image? Or alternatively, is there a module that can take numpy array screenshots at a high FPS?
Even cv2 creates ndarray! Pretty sure YOLO (or other ML model) uses ndarray. More on reddit.com
🌐 r/learnpython
2
2
August 9, 2022
python - Converting Numpy Array to OpenCV Array - Stack Overflow
Just update that newer versions of OpenCV do not require such conversion anymore since the OpenCV array is an NumPy array. 2021-02-02T17:26:59.937Z+00:00 ... Save this answer. ... Show activity on this post. This is what worked for me... Copyimport cv2 import numpy as np #Created an image (really ... More on stackoverflow.com
🌐 stackoverflow.com
python 3.x - Convert Numpy array to image by using OpenCV or PIL - Stack Overflow
I am trying to convert my array to image using OpenCV or PIL libraries, In both of libraries, I am getting the images with mixed up color. This is the way I tried convert Numpy array to image using More on stackoverflow.com
🌐 stackoverflow.com
Building a gray scale image via a numpy array from ultrasonic sensor values - programming - OpenCV
I want to convert its distance readings to an image. I have the readings stored in a numpy array but how do I construct the array so that it is a valid gray scale image? Here is the code I have so far. import maxSonarTTY import numpy as np import cv2 def scale_list(l, to_min, to_max): return ... More on forum.opencv.org
🌐 forum.opencv.org
0
December 15, 2022
🌐
TutorialsPoint
tutorialspoint.com › article › convert-a-numpy-array-to-an-image
Convert a NumPy array to an image
August 9, 2023 - In order to convert the array into an image, we have to pass the array to be converted and the file name as the input arguments to the imshow() function of the opencv library. import cv2 import numpy as np img_array = np.random.randint(0, 256, ...
🌐
Delft Stack
delftstack.com › "delft stack" › "howto" › "python numpy howtos" › "how to save numpy array as image in python"
How to Save NumPy Array as Image in Python | Delft Stack
February 2, 2024 - OpenCV provides various functions for working with images, including saving NumPy arrays as image files using the cv2.imwrite() function.
🌐
Reddit
reddit.com › r/learnpython › how can i turn numpy ndarray into an opencv image? or alternatively, is there a module that can take numpy array screenshots at a high fps?
r/learnpython on Reddit: How can I turn numpy ndarray into an opencv image? Or alternatively, is there a module that can take numpy array screenshots at a high FPS?
August 9, 2022 -

I'm attempting to automate a game using opencv and yolov5. My final problem is that I can't get a script to capture the screen fast enough to follow the objects correctly. I found a module called DXCam that can capture images at astounding speeds, though I can't use them in my algorithm as they are ndarrays and not normal arrays. Is there a way to convert the ndarrays into normal arrays (this process does not need to be fast, I can simply buffer them and alter them after they've been captured)? This is the script that produces the ndarrays:

def record():
    size = (pyautogui.size())
    box = pyautogui.locateOnScreen('game_screen.png', region=(0, 0, size[0], size[1]), grayscale=True, confidence=0.7)

    record_time = 3

    target_fps = 120
    writer = cv2.VideoWriter(
        "output.mp4", cv2.VideoWriter_fourcc(*"mp4v"), target_fps, (box.width, box.height)
    )
    camera = dxcam.create(output_color="RGB")
    camera.start(target_fps=120, video_mode=True, region=(box.left, box.top, box.left + box.width, box.top + box.height))
    cur_time = time.time()
    while time.time() < cur_time + record_time:
        writer.write(camera.get_latest_frame())
    camera.stop()
    writer.release()

Alternatively, are there any faster methods than this? This one for example is not fast enough for my needs (Merely 12-13 frames a second):

def record_bad():
    height = GetSystemMetrics(1)
    width = GetSystemMetrics(0)
    file_name = 'output.mp4v'
    fourcc = cv2.VideoWriter_fourcc(*'MP4V')
    captured_video = cv2.VideoWriter(file_name, fourcc, 120.0, (width, height))
    time_before = time.time()
    frames = []
    while time.time() > time_before + 3:
        img = ImageGrab.grab(bbox=(0, 0, width, height))  # bbox specifies specific region (bbox= x,y,width,height)
        img_final = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRGB)
        frames.append(img_final)
        cv2.waitKey(0)
    for frame in frames:
        captured_video.write(frame)
    captured_video.release()
    cv2.destroyAllWindows()
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert python numpy array to cv2 mat
5 Best Ways to Convert Python Numpy Array to cv2 Mat - Be on the Right Side of Change
February 20, 2024 - import numpy as np import cv2 # Create a random numpy array numpy_array = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8) # Use the numpy array directly in an OpenCV function blurred_image = cv2.GaussianBlur(numpy_array, (5, 5), 0) ...
🌐
YouTube
youtube.com › yes tech media
Convert a Numpy Array to an Image | OpenCV-Python Computer Vision | Malayalam Tutorial | Part-6 - YouTube
Convert a Numpy Array to an Image | OpenCV-Python Computer Vision | Malayalam Tutorial | Part-6____________________________________________________________...
Published: August 20, 2023
Views: 668
Find elsewhere
🌐
AskPython
askpython.com › python › examples › convert-images-to-numpy-arrays
How to Convert Images to Numpy Arrays in Python - AskPython
April 21, 2026 - OpenCV was built for computer vision where BGR was the native format of many camera drivers and codecs. It kept that convention. Use cv2.cvtColor(arr, cv2.COLOR_BGR2RGB) to convert. Q: How do I convert a NumPy array back to an image file?
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 192514 › convert-numpy-arrays-to-images
Convert numpy arrays to images - OpenCV Q&A Forum
May 29, 2018 - Consider the object 'train_x' is a numpy array with dimension (10,28,28), can you please help me in converting these 10 array elements into 10 different images using opencv and name accordingly and store in a location, say "E:\Images". Any reference or example will be helpful. ... Thanks a lot. I ll make sure this will not happen again. ... I was able to get desired result with below set of codes for i in range(train_x.shape[0]): cv2.imwrite("plane"+str(i)+".png",train_x[i])
🌐
Medium
medium.com › @carlosdnotes › create-numpy-images-with-opencv-4b512d5993e4
Create NumPy Images with OpenCV. Create, display, and save images with… | by CarlosD | Medium
October 27, 2025 - Since images in the Python version of OpenCV are NumPy arrays, I will show you how to create, display, and save simple images created with NumPy. I will show you how to do it with a Python script and within Jupyter Lab. ... Once you set up OpenCV as described in my previous post, go to your main.py file. Replace everything inside that file with the following code: #!/usr/bin/env python3 import cv2 as cv import numpy as np def main(): # Set image size, in pixels rows = 6 columns = 8 # Create images black_image = np.ones((rows, columns), dtype=np.uint8) gray_image = np.ones((rows, columns), dtype=np.uint8) * 128 white_image = np.ones((rows, columns), dtype=np.uint8) * 255 # Write images to a file cv.imwrite("./images/black_image.jpg", black_image) cv.imwrite("./images/gray_image.jpg", gray_image) cv.imwrite("./images/white_image.jpg", white_image) # Render…
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-a-numpy-array-to-an-image
Convert a NumPy array to an image - GeeksforGeeks
July 15, 2025 - OpenCV is another popular library for computer vision tasks. It can also convert a NumPy array into an image using its functions like cv2.imshow() for displaying or cv2.imwrite() for saving the array as an image file.
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 225478 › convert-a-2d-numpy-array-to-cv_8uc1-type
Convert a 2D Numpy array to CV_8UC1 type - OpenCV Q&A Forum
images_array = sitk.GetArrayFromImage(images) print(np.amin(images_array),np.amax(images_array)) print(images_array[24].shape, images_array[24].dtype) ... I have found that I can convert it to CV_8UC1 OpenCV type, but I don't know how. I want to convert it because I want to use it with the cv2.equalizeHist method.
🌐
Indian AI Production
indianaiproduction.com › home › blog › explained cv2.imwrite() function in detail | save image
Explained Cv2.Imwrite() Function In Detail | Save Image
April 18, 2021 - #For detail Explanation watch prime video: video link >>> https://youtu.be/6VqbeozUgWQ import cv2 import numpy as np import os rand_array = np.random.randint(255, size = (300,600,3)) cv2.imwrite("rand_np_array.png", rand_array) # imwrite(filename, ...
🌐
Iditect
iditect.com › faq › python › how-to-convert-a-numpy-array-to-and-display-an-image.html
How to convert a numpy array to (and display) an image?
Description: This approach uses OpenCV's cv2.imshow() function to display the image represented by the numpy array.
🌐
OpenCV
forum.opencv.org › t › building-a-gray-scale-image-via-a-numpy-array-from-ultrasonic-sensor-values › 11324
Building a gray scale image via a numpy array from ultrasonic sensor values - programming - OpenCV
December 15, 2022 - Hi all, I have an ultrasonic sensor. I want to convert its distance readings to an image. I have the readings stored in a numpy array but how do I construct the array so that it is a valid gray scale image? Here is the code I have so far. import maxSonarTTY import numpy as np import cv2 def scale_list(l, to_min, to_max): return [scale_number(i, to_min, to_max, min(l), max(l)) for i in l] m=0 raw_sonar_readings=[] while True: m=maxSonarTTY.measure("/dev/ttyUSB0") raw_sonar_r...
🌐
YouTube
youtube.com › watch
Fun Python Exercise - Convert Numbers to Images with NumPy, OpenCV and Pillow - YouTube
In this exercise we will use our NumPy skills to convert numbers into images 💪💪💪 We will see examples of 2 very useful Python image libraries: OpenCV (cv2...
Published: May 31, 2022
🌐
Indian AI Production
indianaiproduction.com › home › blog › explained cv2.imshow() function in detail | show image
Explained cv2.imshow() function in Detail | Show image
January 13, 2021 - import cv2 import numpy as np matx = np.zeros((200,200)) # numpy array with width =200, height=200 cv2.imshow("Zeros matx", matx) # show numpy array cv2.waitKey(0) # wait for ay key to exit window cv2.destroyAllWindows() # close all windows ...
🌐
Roboflow
roboflow.com › use opencv › convert pil image to cv2 image
Convert PIL Image to cv2 image (OpenCV)
You can convert a PIL image to a cv2 image in one line of code. This involves creating a new NumPy array and, often, shuffling the channels of the PIL object from RGB (the format commonly used with PIL) to BGR (the cv2 format).