使用 Python 的铅笔素描图像

人工智能等各类编程培训资料整理,所有资源无秘无压缩-购买会员

图片在 Python 中表示为一组数字。所以我们可以进行各种矩阵操作来得到令人兴奋的结果。在本教程中,将向你展示如何只用几行代码创建“铅笔”草图图像。

这个过程非常简单:

1. 灰度图像

2. 反转颜涩

3. 模糊倒置图像

4. 将减淡混合应用于模糊和灰度图像

我们可以为此选择任何我们想要的图像。将演示如何创建可以应用于任何图像、视频或实时流的对象。

导入库

OpenCV 和 Numpy 是项目所需的唯一库。我们使用以下两行代码导入它们:

import cv2

import numpy as np

读取照片

这是使用 OpenCV 读取存储在磁盘上的图像的命令之一:

frame = cv2.imread("porche.png")

此命令读取位于当前文件夹中的文件“image.png”,并作为帧存储在内存中。但正如我所提到的,这可以是帧序列或通过其他方法加载的图像。

使用 OpenCV 显示图像

下一个重要步骤是在屏幕上显示图像:

cv2.imshow('image', frame)

cv2.waitKey(0)

cv2.destroyAllWindows()

图像将在一个标题为“image”的新窗口中打开:

灰度图像

首先,我们需要对图像进行灰度处理(将其转换为黑白)。我们可以使用 cv2 库或 numpy.

numpy 没有任何用于灰度的内置函数,但我们也可以很容易地将我们的图像转换为灰度,公式如下所示:

grayscale = np.array(np.dot(frame[..., :3], [0.299, 0.587, 0.114]), dtype=np.uint8)

grayscale = np.stack((grayscale,) * 3, axis=-1)

在这里,我们将 RGB 图像通道与适当的值相乘并将它们连接到单个通道。

因此,我们需要返回到 3 层图像,使用 numpy stack 函数来实现。这是我们得到的灰度图像:

反转图像

现在我们需要反转图像,白涩应该变成黑涩。

它简单地从每个图像像素中减去 255 。因为,默认情况下,图像是 8 位的,最多有 256 个涩调:

inverted_img = 255 - grayscale

当我们显示反转图像或将其保存在光盘上时,我们会得到以下图片:

模糊图像

现在我们需要模糊倒置的图像。通过对倒置图像应用高斯滤波器来执行模糊。这里最重要的是高斯函数或 sigma 的方差。随着 sigma 的增加,图像变得更模糊。Sigma 控制涩散量,从而控制模糊程度。可以通过反复试验选择合适的 sigma 值:

blur_img = cv2.GaussianBlur(inverted_img, ksize=(0, 0), sigmaX=5

模糊图像的结果如下所示:

减淡和融合

颜涩减淡和融合模式并通过降低对比度来加亮基涩以反映混合涩。

def dodge(self, front: np.ndarray, back: np.ndarray) -> np.ndarray: """The formula comes from https://en.wikipedia.org/wiki/Blend_modes

Args:

front: (np.ndarray) - front image to be applied to dodge algorithm

back: (np.ndarray) - back image to be applied to dodge algorithm

Returns:

image: (np.ndarray) - dodged image

"""

result = back*255.0 / (255.0-front)

result[result>255] = 255

result[back==255] = 255

return result.astype('uint8')

final_img = self.dodge(blur_img, grayscale)

就是这样!结果如下:

完整代码:

class PencilSketch:

"""Apply pencil sketch effect to an image

"""

def __init__(

self,

blur_simga: int = 5,

ksize: typing.Tuple[int, int] = (0, 0),

sharpen_value: int = None,

kernel: np.ndarray = None,

) -> None:

"""

Args:

blur_simga: (int) - sigma ratio to apply for cv2.GaussianBlur

ksize: (float) - ratio to apply for cv2.GaussianBlur

sharpen_value: (int) - sharpen value to apply in predefined kernel array

kernel: (np.ndarray) - custom kernel to apply in sharpen function

"""

self.blur_simga = blur_simga

self.ksize = ksize

self.sharpen_value = sharpen_value

self.kernel = np.array([[0, -1, 0], [-1, sharpen_value,-1], [0, -1, 0]]) if kernel == None else kernel

def dodge(self, front: np.ndarray, back: np.ndarray) -> np.ndarray:

"""The formula comes from https://en.wikipedia.org/wiki/Blend_modes

Args:

front: (np.ndarray) - front image to be applied to dodge algorithm

back: (np.ndarray) - back image to be applied to dodge algorithm

Returns:

image: (np.ndarray) - dodged image

"""

result = back*255.0 / (255.0-front)

result[result>255] = 255

result[back==255] = 255

return result.astype('uint8')

def sharpen(self, image: np.ndarray) -> np.ndarray: """Sharpen image by defined kernel size

Args:

image: (np.ndarray) - image to be sharpened

Returns:

image: (np.ndarray) - sharpened image

"""

if self.sharpen_value is not None and isinstance(self.sharpen_value, int):

inverted = 255 - image

return 255 - cv2.filter2D(src=inverted, ddepth=-1, kernel=self.kernel)

return image

def __call__(self, frame: np.ndarray) -> np.ndarray:

"""Main function to do pencil sketch

Args:

frame: (np.ndarray) - frame to excecute pencil sketch on

Returns:

frame: (np.ndarray) - processed frame that is pencil sketch type

"""

grayscale = np.array(np.dot(frame[..., :3], [0.299, 0.587, 0.114]), dtype=np.uint8)

grayscale = np.stack((grayscale,) * 3, axis=-1) # convert 1 channel grayscale image to 3 channels grayscale

inverted_img = 255 - grayscale

blur_img = cv2.GaussianBlur(inverted_img, ksize=self.ksize, sigmaX=self.blur_simga)

final_img = self.dodge(blur_img, grayscale)

sharpened_image = self.sharpen(final_img)

return sharpened_image

可以猜测,除了模糊期间的blur_sigma参数外,我们没有太多的空间可以使用。添加了一个额外的功能来锐化图像以解决这个问题。

它与模糊过程非常相似,只是现在,我们不是创建一个核来平均每个像素的强度,而是创建一个内核,使像素强度更高,因此更容易被人眼看到。

下面是关于如何将 PencilSketch 对象用于我们的图像的基本代码:

# main.py

from pencilSketch import PencilSketch

from engine import Engine

if __name__ == '__main__':

pencilSketch = PencilSketch(blur_simga=5)

selfieSegmentation = Engine(image_path='data/porche.jpg', show=True, custom_objects=[pencilSketch])

selfieSegmentation.run()

结论:

这是一个非常不错的教程,不需要任何深入的 Python 知识就可以从任何图像中实现这种“铅笔”素描风格。

免责声明: 1、本站信息来自网络,版权争议与本站无关 2、本站所有主题由该帖子作者发表,该帖子作者与本站享有帖子相关版权 3、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者和本站的同意 4、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责 5、用户所发布的一切软件的解密分析文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。 6、您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 7、请支持正版软件、得到更好的正版服务。 8、如有侵权请立即告知本站,本站将及时予与删除 9、本站所发布的一切破解补丁、注册机和注册信息及软件的解密分析文章和视频仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。
600学习网 » 使用 Python 的铅笔素描图像