如何用一种纯色填充OpenCV图像?
Answers:
将OpenCV C API与结合使用IplImage* img
:
使用cvSet():cvSet(img, CV_RGB(redVal,greenVal,blueVal));
将OpenCV C ++ API与结合使用cv::Mat img
,然后使用以下任一方法:
cv::Mat::operator=(const Scalar& s)
如:
img = cv::Scalar(redVal,greenVal,blueVal);
img.setTo(cv::Scalar(redVal,greenVal,blueVal));
BGR
与此答案不是很相关。跟踪频道顺序通常是用户的责任。
这是在Python中使用cv2的方法:
# Create a blank 300x300 black image
image = np.zeros((300, 300, 3), np.uint8)
# Fill image with red color(set each pixel to red)
image[:] = (0, 0, 255)
这是更完整的示例,说明如何创建填充有特定RGB颜色的新空白图像
import cv2
import numpy as np
def create_blank(width, height, rgb_color=(0, 0, 0)):
"""Create new image(numpy array) filled with certain color in RGB"""
# Create black blank image
image = np.zeros((height, width, 3), np.uint8)
# Since OpenCV uses BGR, convert the color first
color = tuple(reversed(rgb_color))
# Fill image with color
image[:] = color
return image
# Create new blank 300x300 red image
width, height = 300, 300
red = (255, 0, 0)
image = create_blank(width, height, rgb_color=red)
cv2.imwrite('red.jpg', image)
使用numpy.full
。这是一个Python,可创建灰色,蓝色,绿色和红色图像,并以2x2网格显示。
import cv2
import numpy as np
gray_img = np.full((100, 100, 3), 127, np.uint8)
blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)
full_layer = np.full((100, 100), 255, np.uint8)
# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer
cv2.imshow('2x2_grid', np.vstack([
np.hstack([gray_img, blue_img]),
np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')
我亲自制作了此python代码,以更改使用openCV打开或创建的整个图像的颜色。不好意思,我是初学者。
def OpenCvImgColorChanger(img,blue = 0,green = 0,red = 0):
line = 1
ImgColumn = int(img.shape[0])-2
ImgRaw = int(img.shape[1])-2
for j in range(ImgColumn):
for i in range(ImgRaw):
if i == ImgRaw-1:
line +=1
img[line][i][2] = int(red)
img[line][i][1] = int(green)
img[line][i][0] = int(blue)