Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Given two or more colors, how can I find the maximum and minimum color values?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

enter image description here

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:

enter image description here

Masked Image:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading