Create a new RGB OpenCV image using Python?


Question

Possible Duplicate:
OpenCv CreateImage Function isn’t working

I wish to create a new RGB image in OpenCV using Python. I don't want to load the image from a file, just create an empty image ready to do operations on.

1
39
5/23/2017 11:55:09 AM

Accepted Answer

The new cv2 interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:

import cv2  # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)

This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:

blank_image[:,0:width//2] = (255,0,0)      # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)

If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2 interface rather than the older cv one. I made the change recently and have never looked back. You can read more about cv2 at the OpenCV Change Logs.

140
12/28/2018 9:19:59 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon