Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill OpenCV image with one solid color?

How to fill OpenCV image with one solid color?

like image 506
Rella Avatar asked Dec 02 '10 17:12

Rella


People also ask

How do I fill a rectangle in OpenCV?

To fill the rectangle we use the thickness = -1 in the cv2. rectangle() function.

How do I save an image in grayscale in OpenCV?

If you want to save a color image (3D ndarray ) as a grayscale image file, convert it to grayscale with cv2. cvtColor() and cv2. COLOR_BGR2GRAY . If you save 2D ndarray to a file and read it again with cv2.

How do I change the color space in OpenCV?

Changing Color-space For color conversion, we use the function cv. cvtColor(input_image, flag) where flag determines the type of conversion. For HSV, hue range is [0,179], saturation range is [0,255], and value range is [0,255].


2 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, then use either:

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

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

or the more general, mask supporting, cv::Mat::setTo():

img.setTo(cv::Scalar(redVal,greenVal,blueVal)); 
like image 131
Adi Shavit Avatar answered Sep 20 '22 09:09

Adi Shavit


Here's how to do with 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 more complete example how to create new blank image filled with a certain 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) 
like image 44
Kimmo Avatar answered Sep 19 '22 09:09

Kimmo