Reputation: 33
I want to extract the pixels in the regions marked by their respective color. (The normal distribution of the pixels in yellow and red)
I know opencv supports bitwise operation, however, I've only seen it being done with black/white mask.
I thought about using np.where(), I am curious to see if there's a better solution?
Upvotes: 0
Views: 546
Reputation: 207345
You can count the number of red/yellow pixels like this:
#!/usr/bin/env python3
import cv2
import numpy as np
# Load image
im = cv2.imread('abYaj.png')
# Make mask of red pixels - True where red, false elsewhere
redMask = (im[:, :, 0:3] == [0,0,255]).all(2)
# Count red pixels
redTotal = np.count_nonzero(redMask) # redTotal=44158
# Make mask of yellow pixels
yellowMask = (im[:, :, 0:3] == [0,255,255]).all(2)
# Count yellow pixels
yellowTotal = np.count_nonzero(yellowMask) # yellowTotal=356636
Alternatively, you could just use ImageMagick in the Terminal to count them and write no code at all:
magick identify -verbose abYag.png
Image:
Filename: abYaj.png
Format: PNG (Portable Network Graphics)
Mime type: image/png
Class: DirectClass
Geometry: 1024x1024+0+0
Units: Undefined
Colorspace: sRGB
...
...
Colors: 3
Histogram:
647782: (0,0,0,0) #00000000 none
44158: (255,0,0,255) #FF0000FF red <--- HERE
356636: (255,255,0,255) #FFFF00FF yellow <--- HERE
Rendering intent: Perceptual
...
...
Upvotes: 2