在本教程中,我将向您展示如何使用它OpenCV在Python给图像一个卡通效果。
OpenCV它是计算机视觉和机器学习的开源python图书馆。主要用于实时计算机视觉和图像处理。它用于对图像进行不同的操作,然后用不同的技术进行转换。
很多应用程序可以把你的照片变成卡通,但你只需要几行Python代码可以自行完成。
这是我们的测试图像:
elon-musk.jpeg
代码:
importnumpyasnp importcv2
之后,我们读了图像:
filename='elon.jpeg'
然后我们将定义我们resizeImage:
defresizeImage(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) returnresized
我们需要找到轮廓:
deffindCountours(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('Imageaftercountouring',contoured_image) cv2.waitKey(0) cv2.destroyAllWindows() returncontoured_image
之后,我们量化了颜色:
defColorQuantization(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)
然后我们将其转换uint并应用于原始图像
center=np.uint8(center) res=center[label.flatten()] res2=res.reshape((image.shape)) returnres2
if__name__=="__main__": image=cv2.imread(filename) resized_image=resizeImage(image) coloured=ColorQuantization(resized_image) contoured=findCountours(coloured) final_image=contoured save_q=input("Savetheimage?[y]/[n]") ifsave_q=="y": cv2.imwrite("cartoonized_" filename,final_image) print("Imagesaved!")
这是我们的最终结果: