Reputation: 45
import cv2
import numpy as np
img = cv2.imread('img.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,1,2)
for cnt in contours:
approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
if len(approx)==3:
print('Triangle')
elif len(approx)==4:
print('Sq')
elif len(approx)==5:
print('Pen')
elif len(approx) ==6:
print('Hex')
else:
print('Cir')
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
**How to we can find the color of detected shapes in just BRG colors.This code is able to find shapes but I do not have any idea to detect color of this detected shapes. **
Upvotes: 2
Views: 731
Reputation: 53081
Here is one way in Python/OpenCV. Given that you know the contours or polygons, you can create a mask for a given contour. Then use the mask to find all the pixels in the image corresponding to the mask white pixels. The get the mean of those pixels.
Input:
For simplicity here, I simply threshold on the gray level version of the green to make a mask.
import cv2
import numpy as np
# Read image
img = cv2.imread('rgb.png')
# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Define graylevel lower and uppper limits for green
lower = 145
upper = 155
# Create mask
mask = cv2.inRange(gray, lower, upper)
# get mean color
region = img[np.where(mask == 255)]
mean = np.mean(region, axis=0)
print(mean)
# save results
cv2.imwrite('rgb_gray.png', gray)
cv2.imwrite('rgb_mask.png', mask)
cv2.imshow('gray', gray)
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
Gray image:
Mask:
Mean color:
[ 0. 255. 0.]
Which is green as expected.
Upvotes: 0
Reputation: 62
There is certain RGB values of the certain color. There are some websites on which you can upload the image and it give you the exact RGB values of the color you want.
You can write condition where you define the some range of the color which you got from the website, if the color in the image lies in the range you defined then its your color.
Upvotes: 1