Using OpenCV in Python, how can I create a new RGB image? I don't want to load the image from a file, just create an empty image ready to work with.
-
8If I may question the duplicate flag, one question is being answered with cv, and the other with cv2.Arnaud P– Arnaud P2013-09-25 21:04:34 +00:00Commented Sep 25, 2013 at 21:04
-
we need a way to merge questions on stack overflowuser391339– user3913392014-08-28 05:21:09 +00:00Commented Aug 28, 2014 at 5:21
-
to be fair, 8 years later, they both have cv2 answers :)Hugh Perkins– Hugh Perkins2022-11-06 20:43:41 +00:00Commented Nov 6, 2022 at 20:43
-
1I reopened this. Aside from any question about library version: if anything, this should be the canonical for the how-to question - it's much more popular and better received. The other question was phrased as a debugging question, whereas OP here did not encounter any kind of error. The one good answer here also seems higher quality, as it offers better explanation and a relevant documentation link.Karl Knechtel– Karl Knechtel2023-01-15 05:26:54 +00:00Commented Jan 15, 2023 at 5:26
-
1For context: this was previously marked as a duplicate of OpenCv CreateImage Function isn't working, under the old duplicate closure system.Karl Knechtel– Karl Knechtel2023-01-15 05:27:51 +00:00Commented Jan 15, 2023 at 5:27
2 Answers
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.
9 Comments
import cv2 in your example?The following code shows creating a blank RGB image and displaying it:
import numpy as np
import cv2
height, width = 1080, 1920
b, g, r = 0x3E, 0x88, 0xE5 # orange
image = np.zeros((height, width, 3), np.uint8)
image[:, :, 0] = b
image[:, :, 1] = g
image[:, :, 2] = r
cv2.imshow("A New Image", image)
cv2.waitKey(0)