numpy 用于图像处理

1. 转换为灰度图

灰度图的数据可以看成是二维数组,元素取值为0 ~ 255,其中,0为黑色,255为白色。从0到255逐渐由暗色变为亮色。
灰度图转换(ITU-R 601-2亮度变换):
L = R * 299 / 1000 + G * 587 / 1000 + B * 114 / 1000
R,G,B为最低维的数据。
显示灰度图时,需要在imshow中使用参数:
cmap="gray"

import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

def get_color_channels(img):
    img = img.copy()
    channels_num = len(img.shape)
    result = []
    
    channels = np.split(img, channels_num, axis=2)
    for i in channels:
        result.append(i.sum(axis=2)) 
    return result
# img = cv2.imread('/home/geoffrey/图片/小熊猫.png')
img = Image.open('/home/geoffrey/图片/小熊猫.jpeg')
img = np.array(img)
# img.transpose(0,1,2) 
plt.imshow(img)
plt.show()

img.shape
(559, 700, 3)
R, G, B, = get_color_channels(img)
R.shape
(559, 700)
w = np.ones((500,500,3))
plt.imshow(w)
plt.show()

w = np.zeros(shape=(500,500,3), dtype=np.uint8)
plt.imshow(w)
plt.show()

w = np.full(shape=(500,500,3), fill_value=125 , dtype=np.uint8)
w[:] = [0,238,225] # 广播操作
plt.imshow(w)
plt.show()

L = R * 299 / 1000 + G * 587 / 1000 + B * 114 / 1000  
plt.imshow(L, cmap="gray")
plt.show()

temp = np.array([ 0.299,  0.587, 0.114])
plt.imshow(img@temp, cmap="gray")
plt.show()

w = np.zeros(shape=(500,500,3), dtype=np.uint8)
plt.imshow(w)
plt.show()

plt.imshow(L.T, cmap="gray")
plt.show()

test1 = np.array([
    [1,0],
    [0,1]
])
# img.transpose(0,1,2) 
plt.imshow(img)
plt.show()

B_img = img.copy()
B_img[:,:, [0,1]]=0

R_img = img.copy()
R_img[:,:, [0,2]]=0

G_img = img.copy()
G_img[:,:, [2,1]]=0
fig,ax = plt.subplots(2,2)
# 
ax[0,0].imshow(img)
ax[1,1].imshow(R_img)
ax[1,0].imshow(G_img)
ax[0,1].imshow(B_img)
fig.set_size_inches(15, 15)
plt.tight_layout()
plt.show()

t1 = np.concatenate((img, img, img), axis=1) # 横向拼接
t2 = np.concatenate((t1, t1), axis=0)

plt.imshow(t2)
plt.show()

水平镜像 --- 交换行

mirrow_img_x = img[::-1]
plt.imshow(mirrow_img_x)
plt.show()

水平翻转 --- 交换列

mirrow_img_y = img[:,::-1]
plt.imshow(mirrow_img_y)
plt.show()

调换x,y坐标

plt.imshow(img.transpose(1,0,2))
plt.show()

plt.imshow(img.transpose(1,0,2)[::-1])
plt.show()

test = img[:, :, [2,1,0]]
plt.imshow(test)
plt.show()

k = np.random.randint(0, 256, size=(200, 200, 3), dtype=np.uint8)
test = img.copy()
test[300:500,400:600] = k
plt.imshow(test)
plt.show()

t = img.copy()
height=t.shape[0]

li = np.split(t, range(100, height, 30), axis=0)
np.random.shuffle(li)
t = np.concatenate(li, axis=0)
plt.imshow(t)
plt.show()

t = img.copy()

plt.imshow(t[:,:,[2,0,1]])
plt.show()

猜你喜欢

转载自www.cnblogs.com/geoffreyone/p/9897902.html