Erdal.J
Erdal.J

Reputation: 61

How to detect the colors of detected shapes OpenCV

I wrote the code bellow to detect 3D shapes in an image and it works correctly.

Now I need to detect the colors inside the shapes and calculate them.

Could anyone point me where should I start with color detection?

Code for shape detection below, maybe it will be of use:

import cv2
import numpy as np

cv2.imshow('Original Image',rawImage) 
cv2.waitKey(0)

hsv = cv2.cvtColor(rawImage, cv2.COLOR_BGR2HSV)
cv2.imshow('HSV Image',hsv)
cv2.waitKey(0)

hue ,saturation ,value = cv2.split(hsv)
cv2.imshow('Saturation Image',saturation)
cv2.waitKey(0)

retval, thresholded = cv2.threshold(saturation, 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)

for c in cnts:
# compute the center of the contour
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])


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


cv2.imshow('Objects Detected',rawImage)
cv2.waitKey(0)

Centers of shapes founded as we can see, when we do print(second) we get a output of all pixels But I need output just from the pixel inside contour,with this method is that imposible to get values from pixel inside in contour?

Upvotes: 5

Views: 9680

Answers (1)

Kinght 金
Kinght 金

Reputation: 18331

Basic idea:

(1) Convert the image to HSV color space;
(2) Threahold the `S` to find color regions;
(3) Calculate average hsv for each color-region-maskin HSV, then convert into BGR.

For the image:

enter image description here

(1) Convert the image to HSV color space:

enter image description here

(2) Threahold the `S` to find color regions:

enter image description here

(3) Calculate average hsv for each color-region-maskin HSV, then convert into BGR.

enter image description here


Some links maybe useful:

1. just detect color regions: 

(1) How to detect colored patches in an image using OpenCV?

(2) OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

2. detect specific color in HSV:

(1) for green: How to define a threshold value to detect only green colour objects in an image :Opencv

(2) for orange: Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

(3) take of the H of the red: How to find the RED color regions using OpenCV?

3. If you want to crop polygon mask:

(1) Cropping Concave polygon from Image using Opencv python

Upvotes: 5

Related Questions