如何使用Python对图像进行卡通化

  • 时间:2022-03-15 14:07 作者:迈向Python 来源: 阅读:307
  • 扫一扫,手机访问
摘要:在本教程中,我将向你展现如何使用OpenCV在Python中为图像赋予卡通效果。OpenCV是用于计算机视觉和机器学习的开源python库。它主要针对实时计算机视觉和图像解决。它用于对图像执行不同的操作,而后使用不同的技术对其进行转换。许多应用程序可以将您的照片变成卡通,但是您只要几行Python代

在本教程中,我将向你展现如何使用OpenCV在Python中为图像赋予卡通效果。

OpenCV是用于计算机视觉和机器学习的开源python库。它主要针对实时计算机视觉和图像解决。它用于对图像执行不同的操作,而后使用不同的技术对其进行转换。

许多应用程序可以将您的照片变成卡通,但是您只要几行Python代码就可自行完成。

这是我们的测试图像:

elon.jpeg

代码:

import numpy as npimport 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!")

这是我们的最终结果:


  • 全部评论(0)
最新发布的资讯信息
【系统环境|】2FA验证器 验证码如何登录(2024-04-01 20:18)
【系统环境|】怎么做才能建设好外贸网站?(2023-12-20 10:05)
【系统环境|数据库】 潮玩宇宙游戏道具收集方法(2023-12-12 16:13)
【系统环境|】遥遥领先!青否数字人直播系统5.0发布,支持真人接管实时驱动!(2023-10-12 17:31)
【系统环境|服务器应用】克隆自己的数字人形象需要几步?(2023-09-20 17:13)
【系统环境|】Tiktok登录教程(2023-02-13 14:17)
【系统环境|】ZORRO佐罗软件安装教程及一键新机使用方法详细简介(2023-02-10 21:56)
【系统环境|】阿里云 centos 云盘扩容命令(2023-01-10 16:35)
【系统环境|】补单系统搭建补单源码搭建(2022-05-18 11:35)
【系统环境|服务器应用】高端显卡再度登上热搜,竟然是因为“断崖式”的降价(2022-04-12 19:47)
手机二维码手机访问领取大礼包
返回顶部