如何用一种纯色填充OpenCV图像?
答案 0 :(得分:88)
将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);
或the more general, mask supporting, cv::Mat::setTo()
:
img.setTo(cv::Scalar(redVal,greenVal,blueVal));
答案 1 :(得分:21)
以下是如何在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)
答案 2 :(得分:10)
最简单的是使用OpenCV Mat类:
img=cv::Scalar(blue_value, green_value, red_value);
其中img
被定义为cv::Mat
。
答案 3 :(得分:7)
创建一个新的640x480图像并用紫色(红色+蓝色)填充:
cv::Mat mat(480, 640, CV_8UC3, cv::Scalar(255,0,255));
注意:
答案 4 :(得分:6)
对于8位(CV_8U)OpenCV图像,语法为:
Mat img(Mat(nHeight, nWidth, CV_8U);
img = cv::Scalar(50); // or the desired uint8_t value from 0-255
答案 5 :(得分:4)
如果您使用Java for OpenCV,那么您可以使用以下代码。
Mat img = src.clone(); //Clone from the original image
img.setTo(new Scalar(255,255,255)); //This sets the whole image to white, it is R,G,B value
答案 6 :(得分:1)
使用numpy.full
。这是一个Python示例,该示例将整个图像设置为灰色并确保无符号的8位整数结果类型。
import cv2
import numpy as np
img = np.full((100, 100, 3), 127, np.uint8)
cv2.imshow('single color', img)
cv2.waitKey(0)
cv2.destroyWindow('single color')
答案 7 :(得分:1)
color=(200, 100, 255) # sample of a color
img = np.full((100, 100, 3), color, np.uint8)
答案 8 :(得分:0)
我亲自制作了此python代码,以更改使用openCV打开或创建的整个图像的颜色。很抱歉,如果不够好,我是初学者ner。
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)