Skip to content

Instantly share code, notes, and snippets.

@8q
Created June 22, 2018 07:02
Show Gist options
  • Save 8q/05bed424f3d2d9bcd7e0fbd40dc83911 to your computer and use it in GitHub Desktop.
Save 8q/05bed424f3d2d9bcd7e0fbd40dc83911 to your computer and use it in GitHub Desktop.
写真を白黒の線画風の画像にする
# 写真を白黒の線画風の画像にするプログラム
# orig/*.jpg を読み込んで output/*.jpg として出力する
# http://tadaoyamaoka.hatenablog.com/entry/2017/02/19/172744
# http://gori-naru.blogspot.com/2012/11/blog-post_8647.html
import os
import shutil
import glob
import cv2
from tqdm import tqdm
import numpy as np
import math
import multiprocessing as multi
def gamma_compensation(img, gamma):
lookUpTable = np.zeros((256, 1), dtype='uint8')
for i in range(256):
lookUpTable[i][0] = 255 * pow(float(i) / 255, 1.0 / gamma)
return cv2.LUT(img, lookUpTable)
def contrast_adjustment(img, a, b):
lookUpTable = np.zeros((256, 1), dtype='uint8')
for i in range(256):
lookUpTable[i][0] = 255.0 / (1+math.exp(-a*(i-b)/255))
return cv2.LUT(img, lookUpTable)
neiborhood24 = np.array([
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]
], np.uint8)
def worker(path):
orig = cv2.imread(path)
gray = cv2.cvtColor(orig, cv2.COLOR_RGB2GRAY)
img_gamma = gamma_compensation(gray, 2.0)
dilated = cv2.dilate(img_gamma, neiborhood24, iterations=1)
diff = cv2.absdiff(dilated, img_gamma)
contour_tmp = 255 - diff
contour = gamma_compensation(contour_tmp, 0.2)
contour = contrast_adjustment(contour, 8.0, 128)
# cv2.imwrite(f'output/{os.path.basename(path)}', contour)
cv2.imwrite(f'output/{os.path.basename(path)}', cv2.hconcat([
orig, cv2.cvtColor(contour, cv2.COLOR_GRAY2RGB)]))
if __name__ == '__main__':
paths = glob.glob("orig/*.jpg")
with multi.Pool(multi.cpu_count()) as p:
r = list(tqdm(p.imap(worker, paths), total=len(paths)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment