** What is Kuwahara filter ** The Kuwahara filter is a kind of smoothing filter devised by a university professor named Michiyoshi Kuwahara (Wikipedia says). If you want to see, take a look at the bottom of the article) Kuwahara filter -Wikipedia Data processing for SPECT (original paper?)
https://upload.wikimedia.org/wikipedia/commons/4/49/Kuwahara.jpg
To briefly explain the Kuwahara filter, This filter uses the color of each pixel as the average color of the area with the smallest sum of variances in the upper left, upper right, lower left, and lower right square areas of any width around it.
In the image above, to determine the color of the center pixel,
Go through the steps above or the process to get equivalent results. Also, in the image, one side of the square area is 3 pixels, but it can be any width.
** Definition **
import numpy as np
import cv2
def kuwahara (pic, r = 5, resize = False, rate = 0.5): #Original image, square area width -1, Resize or resize ratio
h,w,_=pic.shape
if resize:pic=cv2.resize(pic,(int(w*rate),int(h*rate)));h,w,_=pic.shape
filtered_pic=np.empty_like(pic)
pic=np.pad(pic,((r,r),(r,r),(0,0)),"edge")
ave,var=cv2.integral2(pic)
ave = (ave [: -r-1,: -r-1] + ave [r + 1 :, r + 1:]-ave [r + 1 :,: -r-1] -ave [: -r -1, r + 1 :]) / (r + 1) ** 2 #Batch derivation of average color of area
var = ((var [: -r-1,: -r-1] + var [r + 1 :, r + 1:]-var [r + 1 :,: -r-1]-var [:- r-1, r + 1:]) / (r + 1) ** 2-ave ** 2) .sum (axis = 2) #Batch derivation of regional variance
for i in range(h):
for j in range(w):
filtered_pic [i, j] = np.array ([ave [i, j], ave [i + r, j], ave [i, j + r], ave [i + r, j + r]]) [ np.array ([var [i, j], var [i + r, j], var [i, j + r], var [i + r, j + r]]). argmin ()] #color Decision
return filtered_pic
** Run **
import matplotlib.pyplot as plt
pic = np.array (plt.imread ("input_picture.png ")) Change # input_picture.png to the path of the image you want to filter
filtered_pic=kuwahara(pic,7,True,0.2)
plt.imshow(filtered_pic)
Here are some of the photos I took when I went on a trip to France last year.
The original image
** After applying the filter ** ** A smaller square area ver. **
People, people, people, people > ** Serious painting ** <  ̄Y^Y^Y^Y^Y^Y^ ̄
I introduced it because I was impressed with the texture like drawing on canvas. It's easy so give it a try. I couldn't think of a method that doesn't use the for statement this time, so if the resizing setting is off for a large image, it will take some time. Don't forget to set the third argument to True.
Recommended Posts