本文实例讲述了Python实现PS滤镜中马赛克效果。分享给大家供大家参考,具体如下:
这里利用 Python 实现PS 滤镜中的马赛克效果,具体的算法原理和效果可以参考附录说明,Python示例代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
from skimage import img_as_float
import matplotlib.pyplot as plt
from skimage import io
import random
import numpy as np
file_name = 'D:/Visual Effects/PS Algorithm/4.jpg' ;
img = io.imread(file_name)
img = img_as_float(img)
img_out = img.copy()
row, col, channel = img.shape
half_patch = 10
for i in range (half_patch, row - 1 - half_patch, half_patch):
for j in range (half_patch, col - 1 - half_patch, half_patch):
k1 = random.random() - 0.5
k2 = random.random() - 0.5
m = np.floor(k1 * (half_patch * 2 + 1 ))
n = np.floor(k2 * (half_patch * 2 + 1 ))
h = int ((i + m) % row)
w = int ((j + n) % col)
img_out[i - half_patch:i + half_patch, j - half_patch:j + half_patch, :] = \
img[h, w, :]
plt.figure( 1 )
plt.imshow(img)
plt.axis( 'off' )
plt.figure( 2 )
plt.imshow(img_out)
plt.axis( 'off' )
plt.show()
|
附:PS 滤镜算法原理 ——马赛克
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
% method : 利用邻域的任意一点代替当前邻域所有像素点
% % % % mosaic
clc;
clear all ;
addpath( 'E:\PhotoShop Algortihm\Image Processing\PS Algorithm' );
Image = imread( '4.jpg' );
Image = double(Image);
size_info = size(Image);
height = size_info( 1 );
width = size_info( 2 );
N = 11 ; % 控制邻域大小
Image_out = Image;
for i = 1 + N:N:height - N
for j = 1 + N:N:width - N
k1 = rand() - 0.5 ;
k2 = rand() - 0.5 ;
m = (k1 * (N * 2 - 1 ));
n = (k2 * (N * 2 - 1 ));
h = floor(mod(i + m,height));
w = floor(mod(j + n,width));
if w = = 0 ;
w = width;
end
if h = = 0
h = height;
end
Image_out(i - N:i + N,j - N:j + N, 1 ) = Image(h,w, 1 );
Image_out(i - N:i + N,j - N:j + N, 2 ) = Image(h,w, 2 );
Image_out(i - N:i + N,j - N:j + N, 3 ) = Image(h,w, 3 );
end
end
imshow(Image_out / 255 );
|
原图
效果图
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://blog.csdn.net/matrix_space/article/details/72305574