Advertisement
dan-masek

Untitled

Jan 3rd, 2020
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. import numpy as np
  2. from cv2_41 import cv2
  3. import time
  4.  
  5. im_mask = cv2.imread('mask.png', cv2.IMREAD_GRAYSCALE)
  6. height, width = im_mask.shape
  7.  
  8. res,labels,stats,centroids = cv2.connectedComponentsWithStats(im_mask)
  9.  
  10. def compute_average(frame,i):
  11.     data=frame[labels==i].mean(axis=0)
  12.     return (data[2]-data[1]) # difference between red and green channel is meaningful for me
  13.    
  14. def compute_averages(frame):
  15.     measurements = [ compute_average(frame,i) for i in range(1,len(centroids))]
  16.     return measurements
  17.    
  18. def test(frame, labels):
  19.     stacked = np.dstack([frame, labels])
  20.     stacked = stacked.reshape(-1, 4)
  21.     sorted_stacked = stacked[stacked[:,3].argsort()]
  22.    
  23.     indices = sorted_stacked[:,3].flatten()
  24.     boundaries = np.where(indices[:-1] != indices[1:])[0] + 1
  25.     boundaries = np.append(boundaries, len(stacked))
  26.    
  27.     measurements = []
  28.     for start, end in zip(boundaries[:-1], boundaries[1:]):
  29.         data = sorted_stacked[start:end,:3].mean(axis=0)
  30.         measurements.append(data[2]-data[1])
  31.  
  32.     return measurements
  33.  
  34. while True:
  35.     frame = np.zeros((height, width, 3), np.uint8)
  36.     cv2.randu(frame, (0,0,0), (256,256,256))
  37.     start_time=time.time()
  38.     measurements_a = compute_averages(frame)
  39.     print("Computing A took",time.time()-start_time)
  40.  
  41.     start_time=time.time()
  42.     measurements_b = test(frame, labels)
  43.     print("Computing B took",time.time()-start_time)
  44.  
  45.     print(np.all(np.array(measurements_a) == np.array(measurements_b)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement