Reputation: 71
I have two images, an analysis image and an ROI Mask image (the ROI Mask image is below).
What I want to do is to measure the RGB mean value in an area of the analysis image selected by the ROI Mask image. I am doing this by using a for loop but it takes too long.
Is there any way to make this simpler?
import cv2
import numpy as np
from statistics import mean
img=cv2.imread("Analysis.jpg", 1)
mask=cv2.imread("ROI_Mask.jpg", 0)
height = im.shape[0]
width = im.shape[1]
R_value=[]
G_value=[]
B_value=[]
for x in range(width):
for y in range(height):
if mask[y][x]!=0:
b,g,r=img[y][x]
R_value.append(r)
G_value.append(g)
B_value.append(b)
else:
pass
print(np.mean(R_value))
Upvotes: 5
Views: 350
Reputation: 13743
You can vectorize your code through boolean indexing like this:
b = mask > 0
B_value, G_value, R_value = img[b].T
print(R_value.mean())
Upvotes: 2