image = cv2.imread(IMAGE)
#Change to HSV:
cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
image_blur = cv2.medianBlur(image,9)
#Split in 64 tiles:
NUM_TILES_H = image.shape[1]/ SIZE_TILES
NUM_TILES_V = image.shape[0]/ SIZE_TILES
#Prepare the final image
final_image = np.zeros_like(image)
for i in range(NUM_TILES_H):
for k in range(NUM_TILES_V):
window = image_blur[SIZE_TILES*k:SIZE_TILES*(k+1),SIZE_TILES*i:SIZE_TILES*(i+1),:]
#window_b = cv2.medianBlur(window,7)
#cv2.imwrite(os.path.join(SAVE,'w_'+str(i)+'_'+str(k)+'.jpg'), window)
median_v = np.median(window[:,:,2])
median_s = np.median(window[:,:,1])
final = np.zeros_like(window)
final[(window[:,:,2] > median_v + THRES) ]= [1,1,1]
final_image[SIZE_TILES*k:SIZE_TILES*(k+1),SIZE_TILES*i:SIZE_TILES*(i+1),:] = final
#Fix the final image
kernel = np.ones((3,3), np.uint8)
final_image = cv2.morphologyEx(final_image,cv2.MORPH_OPEN,kernel,iterations=12)
final_image = cv2.morphologyEx(final_image, cv2.MORPH_CLOSE, kernel, iterations=8)
final_image = cv2.medianBlur(final_image,9)
cv2.imwrite(os.path.join(SAVE,'mask.png'), final_image[:,:,0]*255)
masked_image = np.copy(image)
masked_image[final_image[:,:,0] == 0] = 0
cv2.imwrite(os.path.join(SAVE,'masked_image.jpg'), masked_image)