訂閱
糾錯
加入自媒體

使用 Python 的鉛筆素描圖像

圖片在 Python 中表示為一組數字。所以我們可以進行各種矩陣操作來得到令人興奮的結果。在本教程中,將向你展示如何只用幾行代碼創(chuàng)建“鉛筆”草圖圖像。

這個過程非常簡單:

1. 灰度圖像

2. 反轉顏色

3. 模糊倒置圖像

4. 將減淡混合應用于模糊和灰度圖像

我們可以為此選擇任何我們想要的圖像。將演示如何創(chuàng)建可以應用于任何圖像、視頻或實時流的對象。

導入庫

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

當我們顯示反轉圖像或將其保存在光盤上時,我們會得到以下圖片:

模糊圖像

現在我們需要模糊倒置的圖像。通過對倒置圖像應用高斯濾波器來執(zhí)行模糊。這里最重要的是高斯函數或 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參數外,我們沒有太多的空間可以使用。添加了一個額外的功能來銳化圖像以解決這個問題。

它與模糊過程非常相似,只是現在,我們不是創(chuàng)建一個核來平均每個像素的強度,而是創(chuàng)建一個內核,使像素強度更高,因此更容易被人眼看到。

下面是關于如何將 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 知識就可以從任何圖像中實現這種“鉛筆”素描風格。

       原文標題 : 使用 Python 的鉛筆素描圖像

聲明: 本文由入駐維科號的作者撰寫,觀點僅代表作者本人,不代表OFweek立場。如有侵權或其他問題,請聯系舉報。

發(fā)表評論

0條評論,0人參與

請輸入評論內容...

請輸入評論/評論長度6~500個字

您提交的評論過于頻繁,請輸入驗證碼繼續(xù)

暫無評論

暫無評論

人工智能 獵頭職位 更多
掃碼關注公眾號
OFweek人工智能網
獲取更多精彩內容
文章糾錯
x
*文字標題:
*糾錯內容:
聯系郵箱:
*驗 證 碼:

粵公網安備 44030502002758號