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 - 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 - 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 - Reading an 2D array or list with OpenCV - Stack Overflow
I have problems using OpenCV in python, as I'm quite unfamiliar with it. 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... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python 3.x - Creating cv2.VideoCapture() object directly from numpy array image data - Stack Overflow
The purpose is to take data from a virtual camera (from a camera in Gazebo simulation, updating every second) and use Detectron2 (requires data come from cv2.VideoCapture) to recognize other object... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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()
๐ŸŒ
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
๐ŸŒ
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 - ... 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 ...
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-opencv-read-image-cv2-imread
OpenCV Read Image - cv2 imread() - 3 Python Examples
In this Python OpenCV Tutorial, we learned how to use cv2.imread() method to read an image into a Python Array.
๐ŸŒ
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()
Find elsewhere
๐ŸŒ
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, ...
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()

๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ examples โ€บ convert-images-to-numpy-arrays
How to Convert Images to Numpy Arrays in Python - AskPython
April 21, 2026 - If color looks wrong after converting an OpenCV array, flip the channel order first. ... 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.
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
Jupyterjones
jupyterjones.github.io โ€บ Info-Central โ€บ NUMPY-CV2 โ€บ index.html
Arrary processing with Numpy and CV2
The NumPy library is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. Use the following improt convention: Example: Using Numpy to blend two images. You can use OpenCV function addWeighted like: cv2.addWeighted(img1,0.5,img2,0.5,0)` import numpy as np
๐ŸŒ
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()
๐ŸŒ
Indian AI Production
indianaiproduction.com โ€บ home โ€บ blog โ€บ create video from images or numpy array using python opencv | opencv tutorial
Create Video from Images or NumPy Array using Python OpenCV | OpenCV Tutorial
April 18, 2021 - import numpy as np import cv2 import os width = 1280 hieght = 720 channel = 3 fps = 10 sec = 5 fourcc = cv2.VideoWriter_fourcc(*'MP42') video = cv2.VideoWriter('image_to_video.avi', fourcc, float(fps), (width, hieght)) directry = r'C:\Users\kashz\AI Life\AI Projects - IAIP, PTs (Web + Channel)\02 OpenCV\000 opencv tutorial\data\images' img_name_list = os.listdir(directry) for frame_count in range(fps*sec): img_name = np.random.choice(img_name_list) img_path = os.path.join(directry, img_name) img = cv2.imread(img_path) img_resize = cv2.resize(img, (width, hieght)) video.write(img_resize) video.release()