如何使用Python对图像进行卡通化
在本教程中,我将向你展示如何使用OpenCV在Python中为图像赋予卡通效果。
OpenCV是用于计算机视觉和机器学习的开源python库。它主要针对实时计算机视觉和图像处理。它用于对图像执行不同的操作,然后使用不同的技术对其进行转换。
许多应用程序可以将您的照片变成卡通,但是您只需几行Python代码即可自行完成。
这是我们的测试图像:
elon-musk.jpeg
代码:
import numpy as np import cv2
之后,我们阅读了图像:
filename = elon.jpeg
然后我们将定义我们的resizeImage:
def resizeImage(image): scale_ratio = 0.3 width = int(image.shape[1] * scale_ratio) height = int(image.shape[0] * scale_ratio) new_dimensions = (width, height) resized = cv2.resize(image, new_dimensions, interpolation = cv2.INTER_AREA) return resized
我们需要找到轮廓:
def findCountours(image): contoured_image = image gray = cv2.cvtColor(contoured_image, cv2.COLOR_BGR2GRAY) edged = cv2.Canny(gray, 30, 100) contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) cv2.drawContours(contoured_image, contours, contourIdx=-1, color=1, thickness=1) cv2.imshow(Image after countouring, contoured_image) cv2.waitKey(0) cv2.destroyAllWindows() return contoured_image
之后,我们进行颜色量化:
def ColorQuantization(image, K=4): Z = image.reshape((-1, 3))
然后我们将图像转换为numpy float32:
Z = np.float32(Z)
我们还需要定义critera并应用kmeans:
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001) compactness, label, center = cv2.kmeans(Z, K, None, criteria, 1, cv2.KMEANS_RANDOM_CENTERS)
然后我们将其转换uint8并应用于原始图像
center = np.uint8(center) res = center[label.flatten()] res2 = res.reshape((image.shape)) return res2
if __name__ == "__main__":
image = cv2.imread(filename)
resized_image = resizeImage(image)
coloured = ColorQuantization(resized_image)
contoured = findCountours(coloured)
final_image = contoured
save_q = input("Save the image? [y]/[n] ")
if save_q == "y":
cv2.imwrite("cartoonized_"+ filename, final_image)
print("Image saved!")
这是我们的最终结果:
