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
🌐
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 - The code snippet takes a raw data byte array and converts it into a cv2 Mat using cv2.imdecode(). Finally, a quick and easy one-liner approach, if you already have a numpy array with the right type and shape, is to simply pass it into any OpenCV function.
🌐
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 - 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 - Reading an 2D array or list with OpenCV - Stack Overflow
I'm trying to use a two-dimensional array with OpenCV to find lines in it. The data I have never has been an image file and I don't want to create an image just to encode it to an array again. Basically I search for an array alternative for img = cv2.imread(file_path). More on stackoverflow.com
🌐 stackoverflow.com
python - cv2 Writing stream from array - Stack Overflow
This code records video from a webcam: import cv2 w,h = 640,480 cap = cv2.VideoCapture(0,cv2.CAP_DSHOW) out = cv2.VideoWriter('test1.mp4', cv2.VideoWriter_fourcc(*'XVID'), 24.0, (w,h)) while True: ... More on stackoverflow.com
🌐 stackoverflow.com
python - cv2 create video from array of images with specific time - Stack Overflow
I have here the code to generate video from array of images, it is working fine but it only displays each image for less than 1 sec how can i control the displaying time of the images for example p... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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…
🌐
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()
🌐
Python Examples
pythonexamples.org › python-opencv-read-image-cv2-imread
OpenCV Read Image - cv2 imread() - 3 Python Examples
Each element in the array represents grey scale value at the respective pixel. In this example, we will read an image with transparency channel. If there is a transparency channel in the image, then we can pass cv2.IMREAD_UNCHANGED to read the transparency channel along with the color channels. ...
🌐
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 - Syntax: cv2.imshow( windows_name, numpy_array) windows_name: string value numpy_array: 2d or 3d NumPy array
🌐
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, ...
Find elsewhere
🌐
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. Here, no argument means the window will hold infinitely until it is closed manually. ... As we know images are basically multidimensional array ...
🌐
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()
🌐
Medium
medium.com › @rajeshhegde › you-can-use-something-like-this-to-convert-image-into-3d-array-1e862f266d25
You can use cv2 to convert image into an array, | by Rajesh Hegde | Medium
November 11, 2017 - You can use cv2 to convert image into an array, import cv2def read_img(img_path): img = cv2.imread(img_path, cv2.IMREAD_COLOR) img = cv2.resize(img, (256,256)) return imgtrain_img = [] for img_name in images: train_img.append(read_img(TRAIN_PATH ...
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()

🌐
OpenCV
docs.opencv.org › 4.13.0 › d3 › df2 › tutorial_py_basic_ops.html
OpenCV: Basic Operations on Images
>>> import cv2 as cv · >>> img = cv.imread('messi5.jpg') >>> assert img is not None, "file could not be read, check with os.path.exists()" cv::imread · Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR) Loads an image from a file. You can access a pixel value by its row and column coordinates. For BGR image, it returns an array of Blue, Green, Red values.
🌐
Stack Overflow
stackoverflow.com › questions › 65902327 › cv2-writing-stream-from-array
python - cv2 Writing stream from array - Stack Overflow
import cv2 w,h = 640,480 frames = [] cap = cv2.VideoCapture(0,cv2.CAP_DSHOW) out = cv2.VideoWriter('test1.mp4', cv2.VideoWriter_fourcc(*'XVID'), 24.0, (w,h)) while True: key = cv2.waitKey(1) & 0xFF if key == ord('q'): break ret, frame = cap.read() cv2.imshow('frame', frame) frames.append(frame) for frame in frames: out.write(frame) out.release() cap.release() cv2.destroyAllWindows()
🌐
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.eq...
🌐
Analytics Vidhya
analyticsvidhya.com › home › advanced opencv and numpy operations: cropping, copying, and pasting
Advanced OpenCV and NumPy Operations: Cropping, Copying, And Pasting
July 28, 2021 - So our objective is to find the pixel array that makes up the tree, isolate this pixel array, and make portions of the original array be equal to the tree pixel array. It sounds difficult, but it is not and is very interesting. We begin by finding the matrix that comprises the tree as below: tree = image[320:393, 570:665] cv2.imshow('Nature Tree', tree) cv2.waitKey() cv2.destroyAllWindows() Let us display the output of the above pixels to the screen- Output will be seen as follows: Please take note of the following: The image is as it should be.
🌐
AskPython
askpython.com › python › examples › convert-images-to-numpy-arrays
How to Convert Images to Numpy Arrays in Python - AskPython
April 21, 2026 - With OpenCV: cv2.imwrite('output.png', array). With Pillow: Image.fromarray(array).save('output.png').
🌐
Stack Overflow
stackoverflow.com › questions › 62011574 › creating-cv2-videocapture-object-directly-from-numpy-array-image-data
python 3.x - Creating cv2.VideoCapture() object directly from numpy array image data - Stack Overflow
3 "Not Enough Image Data" Error when Converting CV2 Numpy Array into RGB Image · 1 OpenCV (Python) convert an image to a cv2.VideoCapture object · 0 How to get each frame as an image from a cv2.VideoCapture in python · 15 Generate video from numpy arrays with openCV ·