代码来自博客:《女朋友嘲笑我没有艺术气息,我不服!!一气之下我用python画素描人像》
import cv2
import numpy as np
from tkinter import filedialog, Tk
from os import getcwd
from re import findall
def open_path():
root = Tk()
root.withdraw()
file_path = (filedialog.askopenfilename(title='选择图片文件', filetypes=[('All Files', '*')]))
return file_path
def dodgeNaive(image, mask):
width, height = image.shape[:2]
blend = np.zeros((width, height), np.uint8)
for col in range(width):
for row in range(height):
if mask[col, row] == 255:
blend[col, row] = 255
else:
tmp = (image[col, row] << 8) / (255 - mask)
if tmp.any() > 255:
tmp = 255
blend[col, row] = tmp
return blend
def dodgeV2(image, mask):
return cv2.divide(image, 255 - mask, scale=256)
def burnV2(image, mask):
return 255 - cv2.divide(255 - image, 255 - mask, scale=256)
def rgb_to_sketch(src_image_name):
print('转换中......')
img_rgb = cv2.imread(src_image_name)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
img_gray_inv = 255 - img_gray
img_blur = cv2.GaussianBlur(img_gray_inv, ksize=(21, 21),
sigmaX=0, sigmaY=0)
img_blend = dodgeV2(img_gray, img_blur)
cv2.imwrite(dst_image_name, img_blend)
save_path = getcwd() + "\\" + dst_image_name
print('转换完成!!!\n')
print('保存路径:' + save_path)
cv2.imshow(save_path, img_blend)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
print('请选择图片(路径不要含中文):')
src_image_name = open_path()
print(src_image_name + '\n')
image_name = ''.join(findall(r'[^\\/:*?"<>|\r\n]+$', src_image_name))
dst_image_name = 'Sketch_' + image_name
rgb_to_sketch(src_image_name)