Python——修改图片背景颜色

利用Python的skimage包实现修改图片背景色等


修改签名背景,按照灰度图像处理

代码

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
from skimage import io, color
import matplotlib.pyplot as plt


def change_grey_to_white(origin, new):
"""
Change background color for image, such as signature
:param origin: the path of original image
:param new: the path of new image
:return: None
"""
# img = io.imread('./origin.jpeg')
img = io.imread(origin)
io.imshow(img)
plt.show()
img_gray = color.rgb2gray(img)
rows, cols = img_gray.shape
for i in range(rows):
for j in range(cols):
if img_gray[i, j] <= 0.5:
img_gray[i, j] = 0
else:
img_gray[i, j] = 1
io.imshow(img_gray)
plt.show()
io.imsave(new, img_gray)

# example
change_grey_to_white('./origin.jpeg', 'new.jpeg')

说明

  • 这里可接受彩色图片,比如拍照片得到的原始图片
  • 函数会将其转换为灰度图片然后处理,最终输出也是灰度图片
  • 如果需要处理指定灰度,可通过修改判断语句中0.5这个值从而实现(比如修改为区间等)

修改证件照背景,按彩色图像处理

代码

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
from skimage import io
import numpy as np


def change_pixel_color(pixel, old_pixel, new_pixel=None, error=60):
"""
change color for pixel if pixel in range [old_pixel-error, old_pixel+error]
:param pixel:
:param old_pixel:
:param new_pixel:
:param error:
:return: the new pixel
"""
if new_pixel is None:
new_pixel = [255, 255, 255]
similar = True
for i in abs(pixel - old_pixel):
if i > error:
similar = False
break
if similar:
return new_pixel
else:
return pixel


def change_background(origin_path, new_path, new_color, error=60):
"""
change background, auto detect background
:param origin_path:
:param new_path:
:param new_color: target background color
:param error: the error for change color
:return: None
"""
img = io.imread(origin_path)
bg = img[10:30, 10:30, :]
bg_pixel = [1.0 * np.sum(bg[:, :, channel])/bg[:, :, channel].size for channel in range(3)]
print("background color: %s" % bg_pixel)
new_img = np.array([[change_pixel_color(pixel, [0, 160, 234], new_color, error) for pixel in row] for row in img])
io.imshow(new_img)
# import matplotlib.pyplot as plt
# plt.show()
io.imsave(new_path, new_img)


# example
change_background(origin_path="origin.jpeg",
new_path='new.jpeg',
new_color=[0, 255, 255])

说明

  • 自动读取图片的左上角部分像素的平均值作为背景颜色
  • 允许差范围在合适的范围内,可通过error参数调节,该参数不宜过大也不宜过小,可测试多次选择比较合适的