I’m processing images using opencv and part of my problem requires that I iterate over the image by its colors and only display colors which match certain ranges of colors. How can I find the maximum and minimum bgr values?
>Solution :
Here is one way to do that in Python/OpenCV/Numpy. Threshold on the color you want. Then use Numpy to get the min and max colors of each channel.
Input:
import cv2
import numpy as np
# load image
img = cv2.imread('mandril3.jpg')
# create mask for red
lower=np.array((20,40,215))
upper=np.array((100,120,255))
mask = cv2.inRange(img, lower, upper)
# mask the image for viewing
result = img.copy()
result[mask!=255] = (0,0,0)
# separate channels
b,g,r = cv2.split(img)
# compute min and max ranges of red
bmin = np.amin(b[np.where(mask == 255)])
bmax = np.amax(b[np.where(mask == 255)])
gmin = np.amin(g[np.where(mask == 255)])
gmax = np.amax(g[np.where(mask == 255)])
rmin = np.amin(r[np.where(mask == 255)])
rmax = np.amax(r[np.where(mask == 255)])
print("min red:", bmin, gmin, rmin)
print("max red:", bmax, gmax, rmax)
# save results
cv2.imwrite("mandril3_nose_mask.jpg", mask)
cv2.imwrite("mandril3_nose.jpg", result)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Min and Max Colors of the Red Nose:
min red: 20 53 215
max red: 100 120 255
Mask:
Masked Image:


