83

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Phil
  • 46,436
  • 33
  • 110
  • 175
  • 8
    If I may question the duplicate flag, one question is being answered with cv, and the other with cv2. – Arnaud P Sep 25 '13 at 21:04
  • we need a way to merge questions on stack overflow – user391339 Aug 28 '14 at 05:21
  • to be fair, 8 years later, they both have cv2 answers :) – Hugh Perkins Nov 06 '22 at 20:43
  • 1
    I 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 Jan 15 '23 at 05:26
  • 1
    For context: this was previously marked as a duplicate of [OpenCv CreateImage Function isn't working](https://stackoverflow.com/questions/9710520), under the old duplicate closure system. – Karl Knechtel Jan 15 '23 at 05:27

2 Answers2

239

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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
hjweide
  • 11,893
  • 9
  • 45
  • 49
2

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)
Yang_____
  • 117
  • 8