Created
September 29, 2020 09:35
-
-
Save wxupjack/1b0bfbdd6700f69eb42fad1c86324ddf to your computer and use it in GitHub Desktop.
determine whether the photo of surveillance camera is grayscale
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Some surveillance camera has 2 modes, RGB and Infrared. However, | |
the some frames under infrared mode is not completely "gray", they | |
are still 3 channels and value of three channels are not equal. | |
This function accepts image read by opencv(3-d numpy.ndarray), and | |
method ('rgb' or 'hsv'). 'rgb': consider 'gray' means r==g==b of | |
one pixel, smaller difference means geayer. 'hsv': consider gray | |
image is almost black in saturation channel. | |
''' | |
import cv2 | |
import numpy as np | |
# img is numpy.ndarray read by opencv | |
def isGrayImg(img, method='rgb'): | |
if method =='rgb': | |
# for one pixel [r,g,b], diff=(r-g)+(r-b)+(g-b) | |
diff0 = img[:,:,0]-img[:,:,1] | |
diff1 = img[:,:,2]-img[:,:,1] | |
diff2 = img[:,:,0]-img[:,:,2] | |
count = np.count_nonzero(diff0) | |
count += np.count_nonzero(diff1) | |
count += np.count_nonzero(diff2) | |
h,w,c = img.shape | |
percent = count/(h*w*c) | |
return percent < 0.2 # 20% is threshold percentage (0~100%) | |
elif method == 'hsv': | |
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) | |
h,w,c = img.shape | |
# low saturation means gray image | |
avg_saturation = imghsv[:,:,1].sum()/(h*w) | |
return avg_saturation < 10 # 10 is threshold value (0~255) | |
path = 'path/to/image' | |
test_img = cv2.imread(path) | |
print(f'Image {path} is{isGrayImg(test_img, mode='hsv') ? ' ' : ' not '}gray image') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment