4
votes

I need to get the minimum RGB value of a circle. How can I do like the average RGB value method (cv2.mean) appliying a mask? To get the average RGB value of a circle I'm doing:

circle_img = np.zeros((circle_img.shape[0],circle_img.shape[1]), np.uint8)
cv2.circle(circle_img,(x_center,y_center),radio,(255,255,255),-1)
datos_rgb = cv2.mean(color_img, mask=circle_img)

Where color_img is the original image.

To get the minimum RGB value I'm doing:

masked_data = cv2.bitwise_and(color_img, color_img, mask=circle_img)
rgb_min = masked_data.reshape((masked_data.shape[0]*masked_data.shape[1], 3)).min(axis=0)

Where masked_data is the second image (masked circle).

But I'm getting all time the value [0,0,0] because of the background I think... I need to do like the average (cv2.mean) apliying the mask to ignore the black background. There is no pure black in the original image, so it is not possible to get the value [0,0,0]

To get the maximum RGB value it works perfectly doing:

masked_data = cv2.bitwise_and(color_img, color_img, mask=circle_img)
rgb_max = masked_data.reshape((masked_data.shape[0]*masked_data.shape[1], 3)).max(axis=0)

Because the black color [0,0,0] it does not affect here.

This is the original image.

Masked circle

This is the masked circle. Original image

1

1 Answers

4
votes

You may try using only numpy methods to get the results for all required calculations, rather than using OpenCV for some and numpy for others, and in some cases numpy can out-perform OpenCV in terms of execution time. You may use numpys' min, max and mean as:

import cv2
import numpy as np

img = cv2.imread("./assets/11yeJ.jpg")
mask = np.zeros((img.shape[0],img.shape[1]), np.uint8)
cv2.circle(mask, (493, 338), 30, (255, 255, 255), -1)

# Get the indices of mask where value == 255, which may be later used to slice the array.
img_mask = img[np.where(mask == 255)]

img_avg = np.mean(img_mask, axis=0)
img_min = np.min(img_mask, axis=0)
img_max = np.max(img_mask, axis=0)