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
🌐
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, img[, params]) img = cv2.imread("rand_np_array.png") cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()
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
How to convert python np.array to cv2 image - Stack Overflow
In my case I have images of different sizes mono and color and I want to subtract constant value with saturation. The Shapes are HxWx1 or HxWx3 (different datatypes) How to correctly use cv2.subtract for such cases ? Edit: I would like to keep high performance and avoid to allocate temporary arrays ... More on stackoverflow.com
🌐 stackoverflow.com
python - Saving Array as Image in cv2 - Stack Overflow
I'm trying to modify an image using python cv2. So I imported an image to python and represent it as an array. Then I change the Red channel of the image to all 0, then I save the changed array to an More on stackoverflow.com
🌐 stackoverflow.com
python - how to load a color image file as a numpy array? - Stack Overflow
Beware that cv2.imread() returns a numpy array in BGR not RGB. 2017-01-25T20:55:34.88Z+00:00 ... OpenCV seem to have dropped the mode argument. See my answer below for an updated method. 2019-03-09T20:57:50.873Z+00:00 ... PIL (Python Imaging Library) and Numpy work well together. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - In this code, we first create a 100x200 Numpy array with three channels (for RGB). We then fill the left half of the array with orange and the right half with blue. Finally, we use cv2.imwrite() to save the array as an image.
🌐
TutorialsPoint
tutorialspoint.com › 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, ...
🌐
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…
🌐
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 - OpenCV library has powerful function named as cv2.imshow(). Which shows the NumPy array in the form of an Image. cv2.imshow() function takes any size of NumPy array and shows the image in the same size in the window.
🌐
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 - import cv2 import numpy as np image_data = np.array([ [0, 128, 255], [64, 192, 32], [100, 50, 150] ], dtype=np.uint8) cv2.imwrite("output.png", image_data)
🌐
Codegive
codegive.com › blog › cv2_save_numpy_array_as_image.php
Cv2 save numpy array as image
OpenCV's cv2.imwrite() function is the standard way to save an image from a NumPy array to a file on disk. While seemingly simple, there are crucial details related to data types, value ranges, color channels, and file formats that you need to understand to ensure your images are saved correctly.
Find elsewhere
🌐
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()
🌐
Stack Overflow
stackoverflow.com › questions › 65303392 › how-to-convert-python-np-array-to-cv2-image
How to convert python np.array to cv2 image - Stack Overflow
For color image, colorspace are you using? Also, in grayscale you have just one channel, so what are you meaning as saturation? ... @iGian - I have constant value e.g: 3 and I want to subtract it from all channels. The value is equal for all channels. I want to use saturation arithmetic so e.g. for uint8: 2 - 3 = 0 or 250 + 10 = 255. ... No, it does not saturate values: img = np.array([[[200,201,202]]], dtype='uint8') img = (img+100).astype(np.uint8) results in: [[44 45 46]]. Correct answer is: [[255 255 255]]
🌐
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
anjalisingh-ratan.medium.com › image-manipulation-and-processing-using-opencv-and-numpy-d4e5404f3ddd
Image Manipulation and processing using OpenCV and NumPy | by Anjali Singh | Medium
June 12, 2021 - To display image, we can use .imshow() method of the cv2 module, specify the path of image as argument. The waitkey() function take time as an argument in milliseconds as the duration for which the image will hold.
🌐
Python Examples
pythonexamples.org › python-opencv-cv2-imwrite-save-image
OpenCV cv2.imwrite() - Save Image - Python Examples
Python OpenCV cv2.imwrite() - To save image to local storage using Python, use cv2.imwrite() function on OpenCV library. imwrite() writes numpy array as image to the persistent storage.
🌐
OpenCV
docs.opencv.org › 3.4.20 › d3 › df2 › tutorial_py_basic_ops.html
OpenCV: Basic Operations on Images
For individual pixel access, the Numpy array methods, array.item() and array.itemset() are considered better. They always return a scalar, however, so if you want to access all the B,G,R values, you will need to call array.item() separately for each value. ... Image properties include number of rows, columns, and channels; type of image data; number of pixels; etc.
Top answer
1 of 2
1

I think this is what you are looking for. you need to add one more dimension to your list of points using np.expand_dims

import numpy as np
import cv2

my_list = np.array([[1, 0, 1], [2, 0, 1], [2, 0, 2]], dtype=np.uint8)
img = np.expand_dims(my_list, axis=0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 70, 110, apertureSize=3)
# and so on
lines = cv2.HoughLines(edges, 1, np.pi / 180, 150)

EDIT:

As you have clarified that your input list's values are from the gray colour space. you can simply change array datatype to np.uint8 and it will work.

import numpy as np
import cv2

my_list = np.array([[1, 0, 1], [2, 0, 1], [2, 0, 2]], dtype=np.uint8)
edges = cv2.Canny(my_list, 70, 110, apertureSize=3)
# and so on
lines = cv2.HoughLines(edges, 1, np.pi / 180, 150)
2 of 2
1

Just visualizing with a slightly larger 2D array and detecting the diagonal line present in the array with the following code:

my_list = np.eye(100) #np.array([[0,1,0,1],[0,2,0,1],[0,2,0,2]])
gray = (255*my_list/np.max(my_list)).astype('uint8')
edges = cv2.Canny(gray,70,110,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,50)
lines
# array([[[-1.       ,  2.3561945]],
#        [[ 1.       ,  2.3561945]]], dtype=float32)

# original image
plt.imshow(gray, 'gray')
plt.show()

# canny edges detected
plt.imshow(edges)
plt.show()

# lines detected with Hough transform
im = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)

if lines is not None:
    for i in range(len(lines)):
        rho = lines[i][0][0]
        theta = lines[i][0][3]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
        pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))
        print(pt1, pt2)
        cv2.line(im, pt1, pt2, (0,0,255), 2, cv2.LINE_AA)

plt.imshow(im)
plt.show()

🌐
Python Examples
pythonexamples.org › python-opencv-read-image-cv2-imread
OpenCV Read Image - cv2 imread() - 3 Python Examples
To read an image in Python using OpenCV, use cv2.imread() function. imread() returns a numpy array containing values that represents pixel level data. You can read image as a grey scale, color image or image with transparency. Examples for all these scenarios have been provided in this tutorial.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-images-to-numpy-array
How to Convert images to NumPy array? - GeeksforGeeks
September 30, 2022 - <class 'PIL.PngImagePlugin.PngImageFile'> PNG RGB (400, 200) Image is converted and NumPy array information : <class 'numpy.ndarray'> type: float32 shape: (200, 400, 3) converting NumPy array into image: <class 'PIL.Image.Image'> From the above output, we can check that the source image PIL.Image.Image and destination image types are the same. OpenCV version from 3.x has DNN and Caffe frameworks, and they are very helpful to solve deep learning problems. It can be installed by using · pip install opencv-contrib-python · cv2 package has the following methods ·