5

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))

ROI Mask Image

Boann
  • 48,794
  • 16
  • 117
  • 146
Zako
  • 61
  • 3
  • Please explain: by “make this simple” do you mean “make this faster” or “make my code simpler”? If “faster” then please be specific about how fast it is for you and how much faster you want/need it to be? If “simpler” please explain what is over-complex about your current code? – DisappointedByUnaccountableMod Feb 24 '19 at 20:56
  • Thank you very much for question for clarification. I want to make this code faster. More clearly I want to do this without using for loop because double for loop I did causes quite long time. – Zako Feb 25 '19 at 23:55

1 Answers1

2

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())
Tonechas
  • 13,398
  • 16
  • 46
  • 80