Last active
November 14, 2015 12:53
-
-
Save yohhoy/4f762ccf7c7a0bfcccfe to your computer and use it in GitHub Desktop.
Red-Gray image filter (a.k.a. "Apple-nize" filter)
This file contains hidden or 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
#!/usr/bin/env python3 | |
import cv2 | |
import numpy as np | |
import sys | |
def hsv_mask(hsv, h_center, h_range, s_low, v_low): | |
h_low = (h_center - h_range) % 180 | |
h_high = (h_center + h_range) % 180 | |
h, s, v = cv2.split(hsv) | |
kernel = np.ones((3,3), np.uint8) | |
# Hue mask | |
if h_low > h_high: | |
_, m1 = cv2.threshold(h, h_low, 255, cv2.THRESH_BINARY) | |
_, m2 = cv2.threshold(h, h_high, 255, cv2.THRESH_BINARY_INV) | |
mask = cv2.bitwise_or(m1, m2) | |
else: | |
_, acc = cv2.threshold(h, h_low, 255, cv2.THRESH_TOZERO) | |
_, acc = cv2.threshold(acc, h_high, 255, cv2.THRESH_TOZERO_INV) | |
_, mask = cv2.threshold(acc, 0, 255, cv2.THRESH_BINARY) | |
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=2) | |
# Saturation mask | |
_, s_mask = cv2.threshold(s, s_low, 255, cv2.THRESH_BINARY) | |
s_mask = cv2.morphologyEx(s_mask, cv2.MORPH_CLOSE, kernel) | |
# Value(Brightness) mask | |
_, v_mask = cv2.threshold(v, v_low, 255, cv2.THRESH_BINARY) | |
v_mask = cv2.morphologyEx(v_mask, cv2.MORPH_CLOSE, kernel) | |
mask = cv2.bitwise_and(mask, s_mask) | |
mask = cv2.bitwise_and(mask, v_mask) | |
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) | |
return mask | |
def convert(infile, outfile): | |
src = cv2.imread(infile) | |
hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV) | |
mask = hsv_mask(hsv, 10, 30, 64, 64) | |
#cv2.imshow("mask", mask) | |
hsv[:,:,1] = cv2.bitwise_and(hsv[:,:,1], hsv[:,:,1], mask=mask) | |
img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) | |
if outfile: | |
cv2.imwrite(outfile, img) | |
else: | |
cv2.imshow("Preview (press ESC to exit)", img) | |
while cv2.waitKey(33) != 27: | |
pass | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
print("usage: {} <infile> [<outfile>]\n".format(__file__)) | |
sys.exit(0) | |
convert(sys.argv[1], sys.argv[2] if 2 < len(sys.argv) else None) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://qiita.com/yohhoy/items/2176a9d8894adfb6abc7 (ja)