I am working on image operation project where I am using opencv
to read image. After that I am cropping the image and then reading color of each pixel in that cropped image. Color value is returned in BGR format and I am then using webcolors
to get the closing match color name. Below is the code:
import cv2
from pathlib import Path
import os
import imutils
import webcolors
from scipy.spatial import KDTree
from webcolors import hex_to_rgb
def convert_rgb_to_names(rgb_tuple):
css3_db = webcolors.CSS3_HEX_TO_NAMES # css3_hex_to_names
names = []
rgb_values = []
for color_hex, color_name in css3_db.items():
names.append(color_name)
rgb_values.append(hex_to_rgb(color_hex))
kdt_db = KDTree(rgb_values)
distance, index = kdt_db.query(rgb_tuple)
return names[index]
frame = cv2.imread("image.png")
frame = imutils.resize(frame, width=800)
redClip1Img = frame[169:180, 342:351]
htr0, wdr0, dpr0 = redClip1Img.shape
cnt = 0
pixelCnt = 0
for h in range(htr0):
for w in range(wdr0):
p = redClip1Img[h, w]
pixelCnt = pixelCnt 1
blue = p[0]
green = p[1]
red = p[2]
try:
colorName = convert_rgb_to_names((red, green, blue))
if colorName == "indianred":
print("Indian Red color found at pixel {}".format(pixelCnt))
except Exception as e:
print(e)
cv2.imshow(win_name, frame)
cv2.waitKey()
Below is the output:
Indian Red color found at pixel 40
Indian Red color found at pixel 41
Indian Red color found at pixel 42
Indian Red color found at pixel 43
Indian Red color found at pixel 49
Indian Red color found at pixel 50
Indian Red color found at pixel 51
Indian Red color found at pixel 52
As we can see that indianred
color is found consecutively in (40, 41, 42, 43)
and (49, 50, 51, 52)
. I have to write a logic where I have to see if indianred
color is found consecutively in more than 5 pixels, then only we will say it true otherwise false. So in above case it will fail.
Initially I thought of creating list and appending all the pixelCnt
value where color is found and at the end we can check the list if it has more than 5 consecutive values or not. But this will make the process longer. Can anyone please suggest some good tips for this.
Image:
CodePudding user response:
We can count the number of consecutive and check if we got at least five when we see som other color (or when no more pixels). If we only need to see the first group, then we coulda eagerly check for consecutiveCount > 0
and break early.
consecutiveCount = 0;
for h in range(htr0):
for w in range(wdr0):
p = redClip1Img[h, w]
pixelCnt = pixelCnt 1
blue = p[0]
green = p[1]
red = p[2]
try:
colorName = convert_rgb_to_names((red, green, blue))
if colorName == "indianred":
consecutiveCount = consecutiveCount 1;
print("Indian Red color found at pixel {}".format(pixelCnt))
else:
if consecutiveCount > 5:
print("More than 5 consecutive Indian Red found")
consecutiveCount = 0
except Exception as e:
print(e)
if consecutiveCount > 5:
print("More than 5 consecutive Indian Red found")