📜  将图像转换为草图

📅  最后修改于: 2022-05-13 01:57:13.396000             🧑  作者: Mango

将图像转换为草图

在Python,图像只是一个二维整数数组。因此,可以使用各种Python模块进行一些矩阵操作,以获得一些非常有趣的效果。为了将正常图像转换为草图,我们将更改其原始 RGB 值并将其 RGB 值分配为类似于灰色,这样将生成输入图像的草图。

方法一:

  1. 导入所有需要的模块( numpyimageioscipy.ndimageOpenCV
  2. 获取图像输入
  3. 检查图像的RGB值并根据RGB值转换为
  4. 使用cv2.imwrite()显示结局图像输出
Python3
# Python program to Convert Image into sketch
 
 
# import all the required modules
import numpy as np
import imageio
import scipy.ndimage
import cv2
 
 
# take image input and assign variable to it
img = "4.jpeg"
 
 
# function to convert image into sketch
def rgb2gray(rgb):
    # 2 dimensional array to convert image to sketch
    return np.dot(rgb[..., :3], [0.2989, 0.5870, .1140])
 
 
def dodge(front, back):
 
    # if image is greater than 255 (which is not possible) it will convert it to 255
    final_sketch = front*255/(255-back)
    final_sketch[final_sketch > 255] = 255
    final_sketch[back == 255] = 255
 
    # to convert any suitable existing column to categorical type we will use apect function
    # and uint8 is for 8-bit signed integer
    return final_sketch.astype('uint8')
 
 
ss = imageio.imread(img)
gray = rgb2gray(ss)
 
i = 255-gray
 
 
# to convert into a blur image
blur = scipy.ndimage.filters.gaussian_filter(i, sigma=13)
 
 
# calling the fuction
r = dodge(blur, gray)
 
 
cv2.imwrite('4.png', r)


Python3
import cv2
image = cv2.imread('Image.jpg')  # loads an image from the specified file
# convert an image from one color space to another
grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
invert = cv2.bitwise_not(grey_img)  # helps in masking of the image
# sharp edges in images are smoothed while minimizing too much blurring
blur = cv2.GaussianBlur(invert, (21, 21), 0)
invertedblur = cv2.bitwise_not(blur)
sketch = cv2.divide(grey_img, invertedblur, scale=256.0)
cv2.imwrite("sketch.png", sketch)  # converted image is saved as mentioned name



方法二:

导入 cv2:

--> pip install cv2

然后我们将在我们的代码中导入 cv2,之后,我们将使用以下一些函数:

1. imread()-此函数将加载指定文件夹中的图像。



2. cvtColor()-该函数将颜色作为参数,然后将源图像颜色更改为该颜色。

3. bitwise_not()-此函数将通过为其提供遮罩来帮助图像保持属性相同。

4. GaussianBlur()-该函数用于通过锐化图像边缘来修改图像,平滑图像,并将最小化

模糊属性。

5.divide()-这个函数用于图像的归一化,因为它不会失去它以前的属性。

最后将使用imwrite()函数保存图像。

蟒蛇3

import cv2
image = cv2.imread('Image.jpg')  # loads an image from the specified file
# convert an image from one color space to another
grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
invert = cv2.bitwise_not(grey_img)  # helps in masking of the image
# sharp edges in images are smoothed while minimizing too much blurring
blur = cv2.GaussianBlur(invert, (21, 21), 0)
invertedblur = cv2.bitwise_not(blur)
sketch = cv2.divide(grey_img, invertedblur, scale=256.0)
cv2.imwrite("sketch.png", sketch)  # converted image is saved as mentioned name

示例 1:

输入图像:



输出:

示例 2:

输入图像:

输出: