How to fill OpenCV image with one solid color?
To fill the rectangle we use the thickness = -1 in the cv2. rectangle() function.
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.
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].
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));
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With