问题描述
我希望使用Python在OpenCV中创建一个新的RGB图像.我不想从文件中加载图像,只需创建一个空图像即可进行操作.
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.
推荐答案
Python的新cv2
接口集成了 numpy 数组添加到OpenCV框架中,这使操作变得更加简单,因为它们是用简单的多维数组表示的.例如,您的问题将通过以下方式回答:
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)
这将初始化仅黑色的RGB图像.现在,例如,如果您要将图像的左半部分设置为蓝色,而将右半部分设置为绿色,则可以轻松地做到这一点:
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)
如果您想在将来省去很多麻烦,并且不得不问这样的问题,我强烈建议您使用cv2
界面,而不是较旧的cv
界面.我最近进行了更改,并且从没有回头.您可以在 OpenCV更改日志中了解有关cv2
的更多信息.
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创建新的RGB OpenCV图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!