1.Python 图片转漫画风格笔记
个人笔记
2.代码实现
import cv2 as cv
import numpy as np
def read_file(filename):
img = cv.imread(filename)
cv.imshow('origin',img)
return img
def edge_mask(img, line_size, blur_value):
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
gray_blur = cv.medianBlur(gray, blur_value)
edges = cv.adaptiveThreshold(gray_blur, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, line_size, blur_value)
return edges
def color_quantization(img, k):
data = np.float32(img).reshape((-1, 3))
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 20, 0.001)
ret, label, center = cv.kmeans(data, k, None, criteria, 10, cv.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
result = center[label.flatten()]
result = result.reshape(img.shape)
return result
line_size = 7
blur_value = 7
img = read_file("d:\\img\\img4.jpg")
total_color = 9
img1 = color_quantization(img, total_color)
#边缘掩膜
edges = edge_mask(img, line_size, blur_value)
blurred = cv.bilateralFilter(img1, d=7, sigmaColor=200,sigmaSpace=200)
#边缘掩膜与经过颜色处理的图像结合起来
cartoon = cv.bitwise_and(blurred, blurred, mask=edges)
# cv.imshow('o',edges)
# cv.imshow('o1',img1)
cv.imshow('cartoon',cartoon)
#我们在cv.imwrite()的第三个参数中设置了JPEG的编码方式保存图片,并设置了0值,此值在JPEG格式中取值范围是0-100,数值越高,保存的质量就越高。
cv.imwrite('d:\\img\\img4_cartoon.jpg', cartoon, [cv.IMWRITE_JPEG_QUALITY, 50])
cv.waitKey(0)
cv.destroyAllWindows()
3.最后效果图
原图
漫画