本文实例讲述了Python实现PS图像抽象画风效果的方法。分享给大家供大家参考,具体如下:
今天介绍一种基于图像分割和color map 随机采样生成一种抽象画风的图像特效,简单来说,就是先生成一张 color map 图,颜色是渐变的,然后针对要处理的图像,进行分割,这里用的是 SLIC 分割算法,然后从 color map 中随机采样,将采样得到的像素值赋予分割后的图像区域。
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
# -*- coding: utf-8 -*- """ Created on Sun Aug 20 08:31:04 2017 @author: shiyi """ import numpy as np import matplotlib.pyplot as plt from skimage import io from skimage.segmentation import slic import numpy.matlib import random file_name = 'D:/Visual Effects/PS Algorithm/9.jpg' ; img = io.imread(file_name) row, col, channel = img.shape # define the colormap color_map = img.copy() rNW = 0.5 rNE = 1.0 rSW = 0.0 rSE = 0.5 gNW = 0.0 gNE = 0.5 gSW = 0.0 gSE = 1.0 bNW = 1.0 bNE = 0.0 bSW = 0.5 bSE = 0.0 xx = np.arange (col) yy = np.arange (row) x_mask = numpy.matlib.repmat (xx, row, 1 ) y_mask = numpy.matlib.repmat (yy, col, 1 ) y_mask = np.transpose(y_mask) fx = x_mask * 1.0 / col fy = y_mask * 1.0 / row p = rNW + (rNE - rNW) * fx q = rSW + (rSE - rSW) * fx r = ( p + (q - p) * fy ) r[r< 0 ] = 0 r[r> 1 ] = 1 p = gNW + (gNE - gNW) * fx q = gSW + (gSE - gSW) * fx g = ( p + (q - p) * fy ) g[g< 0 ] = 0 g[g> 1 ] = 1 p = bNW + (bNE - bNW) * fx q = bSW + (bSE - bSW) * fx b = ( p + (q - p) * fy ) b[b< 0 ] = 0.0 b[b> 1 ] = 1.0 color_map[:, :, 0 ] = r * 255 color_map[:, :, 1 ] = g * 255 color_map[:, :, 2 ] = b * 255 # segment the image N_block = 100 segments = slic(img, n_segments = N_block, compactness = 10 ) # plt.imshow(segments, plt.cm.gray) seg_img = img.copy() T_mask = img.copy() for i in range (N_block): mask = (segments = = i) T_mask[:, :, 0 ] = mask T_mask[:, :, 1 ] = mask T_mask[:, :, 2 ] = mask x_ind = int (random.random() * (col - 1 )) y_ind = int (random.random() * (row - 1 )) color = color_map[y_ind, x_ind, :] T_img = seg_img * T_mask T_img = color seg_img = seg_img * ( 1 - T_mask) + T_img * T_mask plt.figure( 2 ) plt.imshow(seg_img) plt.show() |
原图:
效果图:
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://blog.csdn.net/matrix_space/article/details/77426802