How to fill an OpenCV image with one solid color?

How to fill an OpenCV image with one solid color?

+52
image-processing opencv
Dec 02 '10 at 17:28
source share
6 answers

Using the OpenCV C API with IplImage* img :

Use cvSet () : cvSet(img, CV_RGB(redVal,greenVal,blueVal));

Using the OpenCV C ++ API with cv::Mat img , use either:

cv::Mat::operator=(const Scalar& s) as in:

 img = cv::Scalar(redVal,greenVal,blueVal); 

or more general, mask support, cv::Mat::setTo() :

 img.setTo(cv::Scalar(redVal,greenVal,blueVal)); 
+76
Dec 02 '10 at 20:18
source share

Here's how to make cv2 in Python:

 # 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) 

Here's a more complete example of creating a new blank image filled with a specific RGB color

 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) 
+12
Apr 7 '14 at 19:10
source share

The simplest is to use the Matrix OpenCV class:

 img=cv::Scalar(blue_value, green_value, red_value); 

where img was defined as cv::Mat .

+9
Nov 06
source share

For an 8-bit (CV_8U) OpenCV image, the syntax is:

 Mat img(Mat(nHeight, nWidth, CV_8U); img = cv::Scalar(50); // or the desired uint8_t value from 0-255 
+4
Mar 26 '15 at 18:56
source share

Create a new 640x480 image and fill it with purple (red + blue):

 cv::Mat mat(480, 640, CV_8UC3, cv::Scalar(255,0,255)); 

Note:

  • height before width
  • type CV_8UC3 means 8-bit unsigned int, 3 channels
  • Color Format: BGR
+3
Mar 12 '17 at 9:55 on
source share

If you use Java for OpenCV, you can use the following code.

 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 
+2
Feb 14 '17 at 21:52
source share



All Articles