微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在python中使所有图像的形状相同

如何解决在python中使所有图像的形状相同

我想利用一些使用 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))

如果您添加值为 alpha255 层,那么您会得到 (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 数组,那么它具有转换颜色的功能。

grayRGB

img_rgb = cv2.cvtColor(img_gray,cv2.COLOR_GRAY2RGB)

grayRBGA

img_rgba = cv2.cvtColor(img_gray,cv2.COLOR_GRAY2RGBA)

RGBRBGA

img_rgba = cv2.cvtColor(img_rgb,cv2.COLOR_RGB2RGBA)

和其他方向

RGBgray

img_gray = cv2.cvtColor(img_rgb,cv2.COLOR_RGB2GRAY)

RBGAgray

img_gray = cv2.cvtColor(img_rgba,cv2.COLOR_RGBA2GRAY)

RGBARBG

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)

文档:Image.fromarray()


编辑:

最小工作示例

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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。