首先,将RGB转换为三维数组,并将红绿蓝三通道分别提取出来,同时获取图片的高度与宽度。
image = Image.open(src_file)
# print(type(image))
img = np.array(image) # 将图片转换成数组形式
print(img.shape) # 数组形式的图片是hwc
img_red = img[:, :, 0]
img_green = img[:, :, 1]
img_blue = img[:, :, 2]
height, width = img_red.shape
对三个通道同一个位置的像素点进行判断,并对三个通道的像素点值进行赋值。
for i in range(0, height):
for j in range(0, width):
if all(img[i, j, :] == 0):
img_red[i, j] = 255
img_blue[i, j] = 0
img_green[i, j] = 0
最后,将三维数组转换为图片进行显示。
new_array = np.array([img_red, img_green, img_blue])
new_array = np.transpose(new_array, (1, 2, 0))
print('new_array', new_array.shape)
pre_res = Image.fromarray(np.uint8(new_array))
附:全部代码
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
fr