原图
图片转换后的成果
源码
import cv2
from PIL import Image, ImageOps, ImageFilter
def toCarttonStyle(picturePath):
imgInput_FileName = picturePath
imgOutput_FileName = picturePath.split(".")[0] + '_cartoon.' + picturePath.split(".")[1]
num_down = 2
num_bilateral = 7
img_rgb = cv2.imread(imgInput_FileName)
img_color = img_rgb
for _ in range(num_down):
img_color = cv2.pyrDown(img_color)
for _ in range(num_bilateral):
img_color = cv2.bilateralFilter(img_color, d=9, sigmaColor=9, sigmaSpace=7)
for _ in range(num_down):
img_color = cv2.pyrUp(img_color)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
img_blur = cv2.medianBlur(img_gray, 7)
img_edge = cv2.adaptiveThreshold(img_blur, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
blockSize=9,
C=2)
height=img_rgb.shape[0]
width = img_rgb.shape[1]
img_color=cv2.resize(img_color,(width,height))
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
img_cartoon = cv2.bitwise_and(img_color, img_edge)
cv2.imwrite(imgOutput_FileName, img_cartoon)
print('文件转换成漫画成功,保存在' + imgOutput_FileName)
def dodge(a, b, alpha):
return min(int(a * 255 / (256 - b * alpha)), 255)
def toSketchStyle(picturePath, blur=25, alpha=1.0):
imgInput_FileName = picturePath
imgOutput_FileName = picturePath.split(".")[0] + '_Sketch.' + picturePath.split(".")[1]
img = Image.open(picturePath)
img1 = img.convert('L')
img2 = img1.copy()
img2 = ImageOps.invert(img2)
for i in range(blur):
img2 = img2.filter(ImageFilter.BLUR)
width, height = img1.size
for x in range(width):
for y in range(height):
a = img1.getpixel((x, y))
b = img2.getpixel((x, y))
img1.putpixel((x, y), dodge(a, b, alpha))
img1.save(imgOutput_FileName)
print('文件转换成漫画成功,保存在' + imgOutput_FileName)
if __name__ == '__main__':
imgInput_FileName = input('输入文件路径:')
while True:
print('1、漫画风格')
print('2、素描风格')
userChoose = input('请选择风格(输入序号即可):')
if userChoose.__eq__('1'):
toCarttonStyle(imgInput_FileName)
break
elif userChoose.__eq__('2'):
toSketchStyle(imgInput_FileName)
break
else:
print('违法输入(请输入序号)')
break