python opencv创建图像_使用Python创建新的RGB OpenCV图像?

1586010002-jmsa.png

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.

解决方案

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.

你可能感兴趣的:(python,opencv创建图像)