Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deal with image special effects with Python

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "Python how to deal with image special effects", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "Python how to deal with image special effects" this article.

Preface

Read image information:

"" Author:XiaoMadate:2021/11/16 "import cv2import numpy as npimport mathimport matplotlib.pyplot as plt img0 = cv2.imread ('E:\ From Zhihu\ For the desk\ cvfifteen1.jpg') img1 = cv2.cvtColor (img0, cv2.COLOR_BGR2GRAY) h, w = img0.shape [: 2] print (h, w) cv2.imshow (" W0 ", img0) cv2.imshow (" W1 ", img1) cv2.waitKey (delay = 0)

The image information obtained is as follows:

386 686

1. Ground glass special effects

The principle of ground glass special effect is to take a pixel randomly to replace it in the neighborhood of the current pixel, so as to achieve the fuzzy effect of ground glass. The code is as follows, a comment has been added, if there are comments in the comment area that you don't understand, let's discuss it together.

# ground glass special effect img2 = np.zeros ((h, w, 3), np.uint8) # generates an all-zero matrix for i in range (0, h-6) as large as the original image: # prevents the following random number from exceeding the edge for j in range (0, w-6): index = int (np.random.random () 6) # 0mm 6 random number (b, g R) = img0 [I + index, j + index] img2 [I, j] = (b, g, r) cv2.imshow ("W2", img2) cv2.waitKey (delay = 0)

The results are as follows:

Because the pixel values of the edges must be subtracted when taking random numbers, unfilled regions inevitably appear on the right boundary and lower boundary of the image.

When I was writing a blog, I suddenly came up with a plan. If we had limited the boundary when creating an all-zero matrix, it would be OK to have a try. As follows:

# ground glass special effects img2 = np.zeros ((h-6, w-6, 3), np.uint8) # generates an all-zero matrix that takes into account the range of random numbers Reduced for i in range (0, h-6): # prevent the following random numbers from exceeding the edge for j in range (0, w-6): index = int (np.random.random () * 6) # 0x6 random numbers (b, g, r) = img0 [I + index, j + index] img2 [I, j] = (b, g, r) cv2.imshow ("W2") Img2) cv2.waitKey (delay = 0)

The ground glass effects generated in the above way will not have unfilled parts, but the size of the image is indeed smaller.

two。 Embossed special effects

The principle of Python to realize the special effect of relief is to outline the boundary curve of the image at first, and then reduce the pixel value around the boundary to get a three-dimensional relief image.

# embossed special effects (need to operate on grayscale images) img3 = np.zeros ((h, w, 3), np.uint8) for i in range (0, h): for j in range (0, w-2): # minus 2 grayP0 = int (img1 [I, j]) grayP1 = int (IMG1 [I) J + 2]) # take the point adjacent to the previous pixel newP = grayP0-grayP1 + 150 # to get the difference Add a constant to increase the three-dimensional sense of relief if newP > 255: newP = 255 if newP

< 0: newP = 0 img3[i, j] = newPcv2.imshow("W3", img3)cv2.waitKey(delay = 0) 得到效果如下: 3. 素描特效 该特效实现较为简单,直接在代码中给出注释: #素描特效img4 = 255 - img1 #对原灰度图像的像素点进行反转blurred = cv2.GaussianBlur(img4, (21, 21), 0) #进行高斯模糊inverted_blurred = 255 - blurred #反转img4 = cv2.divide(img1, inverted_blurred, scale = 127.0) #灰度图像除以倒置的模糊图像得到铅笔素描画cv2.imshow("W4", img4)cv2.waitKey(delay = 0) 4. 怀旧特效 怀旧特效需要专门的 R, G, B 通道的转换公式来对图像的三个通道进行处理,转换公式为:

The implementation code is as follows:

# nostalgic special effects img5 = np.zeros ((h, w, 3), np.uint8) for i in range (0, h): for j in range (0, w): B = 0.272 * img0 [I, j] [2] + 0.534 * img0 [I, j] [1] + 0.131 * img0 [I, j] [0] G = 0.349 * img0 [I, j] [2] + 0.686 * img0 [I J] [1] + 0.168 * img0 [I, j] [0] R = 0.393 * img0 [I, j] [2] + 0.769 * img0 [I, j] [1] + 0.189 * img0 [I, j] [0] if B > 255B = 255if G > 255G = 255if R > 255R = 255img5 [I J] = np.uint8 ((B, G, R)) cv2.imshow ("W5", img5) cv2.waitKey (delay = 0)

The results are as follows:

The amount of calculation of this special effect is a little larger than the previous ones, so it is necessary to traverse the pixels and then calculate the values of the three channels of each point.

5. Fleeting special effects

Compared with the previous nostalgic special effects, the fleeting special effect only needs to make a simple adjustment to the blue channel (B) of each pixel in the image, first by its open root sign, and then by multiplying it by a parameter. The implementation code is as follows:

# Special effects img6 = np.zeros ((h, w, 3), np.uint8) for i in range (0, h): for j in range (0, w): B = math.sqrt (img0 [I, j] [0]) * 14 # B channel squared by the parameter 14 G = img0 [I, j] [1] R = img0 [I J] [2] if B > 255B = 255img6 [I, j] = np.uint8 ((B, G, R)) cv2.imshow ("W6", img6) cv2.waitKey (delay = 0)

You can modify more parameters for debugging and observe the effect under different parameters.

6. Water wave special effect

The water wave special effect is to use the trigonometric function to get the transfer function of the ripple, and then generate the special effect according to the set center. This part of the algorithm is a bit difficult, just try it a few more times. In the future, bloggers will have time to produce a special introduction to the water wave effect blog post. The implementation code is as follows:

# Water wave effect img7 = np.zeros ((h, w, 3)) Np.uint8) wavelength = 20 # defines the special effect wavelength of water wave amplitude = 30 # amplitude phase = math.pi / 4 # phase centreX = 0.5 # water wave center point XcentreY = 0.5 # Center point of water wave Yradius = min (h W) / 2icentreX = w*centreX # Water wave coverage width icentreY = h*centreY # Water wave coverage height for i in range (0, h): for j in range (0 W): dx = j-icentreX dy = I-icentreY distance = dx * dx + dy * dy if distance > radius * radius: X = j y = I else: # calculate the water wave region distance = math.sqrt (distance) amount = amplitude * math.sin (distance / wavelength * 2 * math.pi-phase) Amount = amount * (radius-distance) / radius amount = amount * wavelength / (distance + 0.0001) x = j + dx * amount y = I + dy * amount # Boundary judgment if x

< 0: x = 0 if x >

= w-1: X = w-2 if y

< 0: y = 0 if y >

= h-1: y = h-2p = x-int (x) Q = y-int (y) # Image water wave assignment img7 [I, j,:] = (1-p) * (1-Q) * img0 [int (y), int (x),:] + p * (1-Q) * img0 [int (y), int (x) :] + (1-p) * Q * img0 [int (y), int (x),:] + p * Q * img0 [int (y), int (x),:] cv2.imshow ("W7", img7) cv2.waitKey (delay = 0)

The results are as follows:

As this picture happens to be near the ripple is the hair, resulting in the ripple is not very clear, you can try a few pictures to see the effect of the algorithm.

7. Cartoon special effects

The main principle of the special effect is to extract the boundary outline of the image, and then compare it with the original image to get the final cartoon effect. The code is as follows, and comments have been added:

# cartoon special effects num_bilateral = 7 # define the number of bilateral filters for i in range (num_bilateral): # bilateral filtering processing to remove noise Reserved boundary img_color = cv2.bilateralFilter (img0, d = 9, sigmaColor = 5, sigmaSpace = 3) img_blur = cv2.medianBlur (img1, 7) # median filtering img_edge = cv2.adaptiveThreshold (img_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize = 5, C = 2) # Edge detection and adaptive threshold processing Extraction boundary img_edge = cv2.cvtColor (img_edge, cv2.COLOR_GRAY2RGB) # convert back to color image img8 = cv2.bitwise_and (img0, img_edge) # image and operation cv2.imshow ('W8, img8) cv2.waitKey (delay = 0)

The results are as follows:

If you are not satisfied with the results achieved, you can constantly adjust the parameters of bilateral filtering and median filtering until a more satisfactory result is found.

8. Summarize all the images into one picture

Basic operation, there is nothing to comment on, go directly to the code:

# Save all images in one picture plt.rcParams ['font.family'] =' SimHei'imgs = [img0, img1, img2, img3, img4, img5, img6, img7, img8] titles = ['original image', 'grayscale image', 'ground glass special effects', 'relief special effects', 'sketch special effects', 'nostalgic special effects', 'fleeting special effects', 'water wave special effects' For i in range (9): imgs [I] = cv2.cvtColor (imgs [I], cv2.COLOR_BGR2RGB) plt.subplot (3,3, I + 1) plt.imshow (imgs [I]) plt.title (titles [I]) plt.xticks ([]) plt.yticks ([]) plt.suptitle ('Image Special effects processing') plt.savefig ('E:\ From Zhihu\ For the desk\ cvfifteenresult.jpg' Dpi = 1080) plt.show ()

Get the final general picture:

9. Overall code

Modify the image reading path and use it. Again, it is recommended to do it slowly from the beginning, of course, it doesn't matter if you just want to generate a sketch or relief for your girlfriend.

"" Author:XiaoMadate:2021/11/16 "import cv2import numpy as npimport mathimport matplotlib.pyplot as plt img0 = cv2.imread ('E:\ From Zhihu\ For the desk\ cvfifteen1.jpg') img1 = cv2.cvtColor (img0, cv2.COLOR_BGR2GRAY) h, w = img0.shape [: 2] print (h, w) cv2.imshow (" W0 ", img0) cv2.imshow (" W1 ", img1) cv2.waitKey (delay = 0) # ground glass special effects img2 = np.zeros ((h-6, w-6, 3) Np.uint8) # generates an all-zero matrix that takes into account the range of random numbers Reduced for i in range (0, h-6): # prevent the following random numbers from exceeding the edge for j in range (0, w-6): index = int (np.random.random () * 6) # 0x6 random numbers (b, g, r) = img0 [I + index, j + index] img2 [I, j] = (b, g, r) cv2.imshow ("W2") Img2) cv2.waitKey (delay = 0) # relief special effects (need to operate on grayscale images) img3 = np.zeros ((h, w, 3), np.uint8) for i in range (0, h): for j in range (0, w-2): # minus 2 grayP0 = int (img1 [I, j]) grayP1 = int (IMG1 [I) J + 2]) # take the point adjacent to the previous pixel newP = grayP0-grayP1 + 150 # to get the difference Add a constant to increase the three-dimensional sense of relief if newP > 255: newP = 255 if newP

< 0: newP = 0 img3[i, j] = newPcv2.imshow("W3", img3)cv2.waitKey(delay = 0)#素描特效img4 = 255 - img1 #对原灰度图像的像素点进行反转blurred = cv2.GaussianBlur(img4, (21, 21), 0) #进行高斯模糊inverted_blurred = 255 - blurred #反转img4 = cv2.divide(img1, inverted_blurred, scale = 127.0) #灰度图像除以倒置的模糊图像得到铅笔素描画cv2.imshow("W4", img4)cv2.waitKey(delay = 0)#怀旧特效img5 = np.zeros((h, w, 3), np.uint8)for i in range(0, h): for j in range(0, w): B = 0.272 * img0[i, j][2] + 0.534 * img0[i, j][1] + 0.131 * img0[i, j][0] G = 0.349 * img0[i, j][2] + 0.686 * img0[i, j][1] + 0.168 * img0[i, j][0] R = 0.393 * img0[i, j][2] + 0.769 * img0[i, j][1] + 0.189 * img0[i, j][0] if B >

R = 255img5 [I, j] = np.uint8 ((B, G, R)) cv2.imshow ("W5", img5) cv2.waitKey (delay = 0) # Special effects img6 = np.zeros ((h, w, 3), np.uint8) for i in range (0, h): for j in range (0) W): B = math.sqrt (img0 [I, j] [0]) * 14 # B channel squared by parameter 14G = img0 [I, j] [1] R = img0 [I, j] [2] if B > 255B = 255img6 [I, j] = np.uint8 ((B, G, R)) cv2.imshow ("W6") Img6) cv2.waitKey (delay = 0) # Water wave special effect img7 = np.zeros (h, w, 3) Np.uint8) wavelength = 20 # defines the special effect wavelength of water wave amplitude = 30 # amplitude phase = math.pi / 4 # phase centreX = 0.5 # water wave center point XcentreY = 0.5 # Center point of water wave Yradius = min (h W) / 2icentreX = w*centreX # Water wave coverage width icentreY = h*centreY # Water wave coverage height for i in range (0, h): for j in range (0 W): dx = j-icentreX dy = I-icentreY distance = dx * dx + dy * dy if distance > radius * radius: X = j y = I else: # calculate the water wave region distance = math.sqrt (distance) amount = amplitude * math.sin (distance / wavelength * 2 * math.pi-phase) Amount = amount * (radius-distance) / radius amount = amount * wavelength / (distance + 0.0001) x = j + dx * amount y = I + dy * amount # Boundary judgment if x

< 0: x = 0 if x >

= w-1: X = w-2 if y

< 0: y = 0 if y >

= h-1: y = h-2p = x-int (x) Q = y-int (y) # Image water wave assignment img7 [I, j,:] = (1-p) * (1-Q) * img0 [int (y), int (x),:] + p * (1-Q) * img0 [int (y), int (x) :] + (1-p) * Q * img0 [int (y), int (x),:] + p * Q * img0 [int (y), int (x),:] cv2.imshow ("W7") Img7) cv2.waitKey (delay = 0) # cartoon special effects num_bilateral = 7 # define the number of bilateral filters for i in range (num_bilateral): # bilateral filtering processing img_color = cv2.bilateralFilter (img0, d = 9, sigmaColor = 5, sigmaSpace = 3) img_blur = cv2.medianBlur (img1 7) # median filtering processing img_edge = cv2.adaptiveThreshold (img_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize = 5, C = 2) # Edge detection and adaptive threshold processing img_edge = cv2.cvtColor (img_edge, cv2.COLOR_GRAY2RGB) # convert back to color image img8 = cv2.bitwise_and (img0 Img_edge) # cv2.imshow ('W8 image, img8) cv2.waitKey (delay = 0) # Save all images in one picture plt.rcParams ['font.family'] =' SimHei'imgs = [img0, img1, img2, img3, img4, img5, img6, img7, img8] titles = ['original image', 'grayscale image', 'ground glass special effects', 'relief special effects', 'sketch special effects', 'nostalgic special effects' For i in range (9): imgs [I] = cv2.cvtColor (imgs [I], cv2.COLOR_BGR2RGB) plt.subplot (3,3) I + 1) plt.imshow (IMGS [I]) plt.title (titles [I]) plt.xticks ([]) plt.yticks ([]) plt.suptitle ('Image Special effects processing') plt.savefig ('E:\ From Zhihu\ For the desk\ cvfifteenresult.jpg', dpi = 1080) plt.show () above is all the content of the article "how Python handles Image Special effects" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report