顾名思义,图像反转即反转图像灰度级,可以得到等效的照片底片
设一幅图片的灰度级为,则反转图像公式如下:
s为目标图像的像素点的像素值,r为原图像像素点的像素值
下面使用Python实现图像反转:
使用的图像数据为:
导入待使用的第三方库:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
读取图片,并查看图片大小和通道数:
img = Image.open('灰原.jpg')
np.shape(img)
(300, 533, 3)
原图像大小为300*533像素的, RGB三通道彩色图片
可视化:
plt.axis('off')
plt.imshow(img)
plt.show()
将图像数据转换为numpy数组:
img_data = np.array(img)
图像反转函数:
def Image_rollovers(img, func):
img_data = np.array(img)
a = np.shape(img_data)
new_img = []
for i in range(a[0]):
new_row = []
for j in range(a[1]):
data = list(img_data[i][j])
new_data = func(data)
new_row.append(np.array(new_data))
new_img.append(np.array(new_row))
return new_img
def rollovers(data):
new_data = []
for k in data:
new_data.append(int(255-k))
return new_data
调用函数并查看结果:
new_img = Image_rollovers(img, rollovers)
new_img = np.array(new_img)
new_img = Image.fromarray(new_img.astype('uint8')).convert('RGB')
plt.figure(figsize=(72,128))
plt.subplot(121)
plt.axis('off')
gray1 = new_img.convert('L')
plt.imshow(gray1, cmap='gray')
plt.subplot(122)
plt.axis('off')
plt.imshow(img, cmap='gray')
plt.show()
左侧为目标图像,左侧为原图像