Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Color of single shape detected,how to detect color of each shape?

Hi, Iam trying on Python to detect each shape colors.Code bellow works correctly but detects just one shape color.I need to detect each shape colors..I just defined Blue and Green color boundaries,just to check then I will and for other colors.. Any solution, where Iam doing wrong ? Can anyone help me pls..

import numpy as np
import cv2
rawImage = cv2.imread('C:\Users\erdal.alimovski\Desktop\pict2.jpg')
cv2.imshow('Original Image',rawImage)
cv2.waitKey(0)

gray = cv2.cvtColor(rawImage.copy(), cv2.COLOR_BGR2GRAY)
cv2.imshow('HSV Image',gray)
cv2.waitKey(0)

retval, thresholded = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imshow('Thresholded Image',thresholded)
cv2.waitKey(0)

medianFiltered = cv2.medianBlur(thresholded,5)
cv2.imshow('Median Filtered Image',medianFiltered)
 cv2.waitKey(0)

cnts, hierarchy = cv2.findContours(medianFiltered, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

lower = np.array([0,50,30], dtype = "uint8")
upper = np.array([90,255,255], dtype = "uint8")

bluelower = np.array([101,50,38],dtype = "uint8")
blueupper = np.array([255,255,110],dtype = "uint8")

for c in cnts:
   M = cv2.moments(c)
   cX = int(M["m10"] / M["m00"])
   cY = int(M["m01"] / M["m00"])
   cc = cX,cY

first = cv2.drawContours(rawImage, [c], -1, (0, 255, 0), 2)

x, y, w, h = cv2.boundingRect(c)
blurred_cnt_image = cv2.blur(rawImage[y:y+h, x:x+w], (5,5))
green_mask = cv2.inRange(blurred_cnt_image, lower, upper)
green_part = cv2.bitwise_and(blurred_cnt_image, blurred_cnt_image, mask = green_mask)
green_part_as_gray = cv2.cvtColor(green_part, cv2.COLOR_BGR2GRAY)
all_pixels = float((green_part.shape[0]*green_part.shape[1])/100)
green_pixels = float(cv2.countNonZero(green_part_as_gray))

blurred_image = cv2.blur(rawImage[y:y+h, x:x+w], (5,5))
blue_mask = cv2.inRange(blurred_image, bluelower, blueupper)
blue_part = cv2.bitwise_and(blurred_image, blurred_image, mask = blue_mask)
blue_part_as_gray = cv2.cvtColor(blue_part, cv2.COLOR_BGR2GRAY)
most_pixels = float((green_part.shape[0]*blue_part.shape[1])/100)
blue_pixels = float(cv2.countNonZero(blue_part_as_gray))

percent = int(green_pixels/all_pixels)
percentb=int(blue_pixels/all_pixels)

if int(percent) > 2:
    cv2.putText(rawImage, str(percent)+"% green",  (cc),cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255, 255), 2)
else:
    cv2.putText(rawImage, str(percentb) + "% blue",  (cc), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)



cv2.imshow("raw", rawImage)
cv2.waitKey(10000)

Iam Gettin otuput like this:image description

But I need to detect and other circles color.