问题描述
我想利用一些使用 CNN 分类的图像。
然而,问题是图像形状不同,例如
for i in range(1,len(x_train)):
print(print(x_train_resize[i].shape))
这显示了我正在使用的所有图像的图像形状,这给出了
的输出None
(100,100)
None
(100,100,3)
None
(100,4)
如上所示,有没有办法使我拥有的图像的形状与 (100,1) 或 (100,3)
解决方法
(100,100)
表示 grayscale
图像。
(100,100,3)
表示 RGB
图像。
(100,4)
表示 RGBA
图像。
如果您有形状为 grayscale
的 numpy img_gray
图像 (100,100)
,那么您可以复制图层以创建 (100,3)
,就像 RGB
img_rgb = np.dstack((img_gray,img_gray,img_gray))
如果您添加值为 alpha
的 255
层,那么您会得到 (100,4)
就像 RGBA
alpha = np.ones((100,100),dtype='uint8') * 255
img_rgba = np.dstack((img_rgb,alpha))
如果你有 img_rgba
和 (100,4)
那么你可以跳过 alpha
层得到 img_rgb
img_rgb = img_rgba[:,:,:3]
将 rgb
转换为 grayscale
您可以计算
img_gray = (img_rgb[:,0] + img_rgb[:,1] + img_rgb[:,2]) // 3
但更好的是公式 GRAY = 0.2126 * R + 0.7152 * G + 0.0722 * B
img_gray = int(0.2126 * img_rgb[:,0] + 0.7152 * img_rgb[:,1] + 0.0722 * img_rgb[:,2])
维基百科:Converting colour to greyscale
如果您使用 OpenCV
也使用 numpy 数组,那么它具有转换颜色的功能。
gray
到 RGB
img_rgb = cv2.cvtColor(img_gray,cv2.COLOR_GRAY2RGB)
gray
到 RBGA
img_rgba = cv2.cvtColor(img_gray,cv2.COLOR_GRAY2RGBA)
RGB
到 RBGA
img_rgba = cv2.cvtColor(img_rgb,cv2.COLOR_RGB2RGBA)
和其他方向
RGB
到 gray
img_gray = cv2.cvtColor(img_rgb,cv2.COLOR_RGB2GRAY)
RBGA
到 gray
img_gray = cv2.cvtColor(img_rgba,cv2.COLOR_RGBA2GRAY)
RGBA
到 RBG
img_rgb = cv2.cvtColor(img_rgba,cv2.COLOR_RGBA2RGB)
您也可以使用 pillow
Image.convert 但它需要
- 将
numpy array
转换为pillow Image
-img = Image.fromarray(array)
, - 转换颜色 -
img = img.convert(...)
, - 将
pillow Image
转换回numpy array
-array = np.asarray(img)
。
编辑:
最小工作示例
import numpy as np
img_gray = np.zeros((100,dtype='uint8')
# create image with cross
for y in range(100):
img_gray[y,y] = int(255 * (y/100))
img_gray[y,99-y] = int(255 * (y/100))
print('img_gray.shape:',img_gray.shape) # (100,100)
img_rgb = np.dstack((img_gray,img_gray))
print('img_rgb.shape:',img_rgb.shape) # (100,3)
alpha = np.ones((100,alpha))
print('img_rgba.shape:',img_rgba.shape)
import matplotlib.pyplot as plt
plt.imshow(img_gray)
plt.show()
plt.imshow(img_rgb)
plt.show()
plt.imshow(img_rgba)
plt.show()
# --- OpenCV ---
import cv2
img_cv2_rgb = cv2.cvtColor(img_gray,cv2.COLOR_GRAY2RGB)
print('img_cv2_rgb.shape:',img_cv2_rgb.shape)
img_cv2_rgba = cv2.cvtColor(img_gray,cv2.COLOR_GRAY2RGBA)
print('img_cv2_rgba.shape:',img_cv2_rgba.shape)
img_cv2_rgba2 = cv2.cvtColor(img_cv2_rgb,cv2.COLOR_RGB2RGBA)
print('img_cv2_rgba2.shape:',img_cv2_rgba2.shape)
cv2.imshow('gray',img_gray)
cv2.imshow('rgb',img_cv2_rgb)
cv2.imshow('rgba',img_cv2_rgba)
cv2.waitKey(0)
cv2.destroyAllWindows()