Python 将 3 通道 rgb 彩色图像更改为 1 通道灰色的速度有多快?

新手上路,请多包涵

我在包含原始像素数据的 4D 数组中有近 40000 张图像 - (示例数、宽度、高度、通道)。每幅图像的宽度为 32 像素,高度为 32 像素,并且有 3 个 RGB 颜色通道。我想将它们更改为灰度图像(从 3 个带 rgb 的通道得到 1 个带强度)。我怎样才能做得很快?我的代码:

 import pickle
import cv2
training_file = "/train.p"

with open(training_file, mode='rb') as f:
train = pickle.load(f)
X_train = train['features']

def rgb2gray(rgb):
    r, g, b = rgb[0], rgb[1], rgb[2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray

X_train_gray = X_train.copy()

for i in range (X_train_gray.shape[0]):
    for j in range (X_train_gray.shape[1]):
        for k in range (X_train_gray.shape[2]):
            rgb = X_train_gray[i,j,k]
            gray = rgb2gray(rgb)
            X_train_gray[i,j,k] = gray

print("X_train image data shape =", X_train.shape)
print("X_train_grey image data shape =", X_train_gray.shape)

结果:

X_train_grey 图像数据shape = (40000, 32, 32, 3)

X_train_grey 图像数据shape = (40000, 32, 32, 1)

这很好,但是需要很多时间。

我也尝试使用 cv2:

 X_train_gray = X_train[0].copy()
print("X_train_grey image data shape =", X_train_gray.shape)
X_train_gray = cv2.cvtColor(X_train_gray, cv2.COLOR_BGR2GRAY)
print("X_train_grey image data shape =", X_train_gray.shape)

结果:

X_train_grey 图像数据shape = (32, 32, 3)

X_train_grey 图像数据shape = (32, 32)

但是我失去了强度并且不知道如何获得它。

那么如何快速将此图像从 3 通道 rgb 更改为 1 通道灰色?

原文由 kamil 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 742
2 个回答

我以前遇到过这个问题。这是最好的方法:您的代码是正确的,但需要进行更多更改以适合灰度图像。这是代码:

 ii = cv2.imread("0.png")
gray_image = cv2.cvtColor(ii, cv2.COLOR_BGR2GRAY)
print(gray_image)
plt.imshow(gray_image,cmap='Greys')
plt.show()

这是结果:

[[196 196 197 195 195 194 195 197 196 195 194 194 196 194 196 189 188 195 195 196 197 198 195 194 194 195 193 191] 。 . . [194 194 193 193 191 189 193 193 192 193 191 194 193 192 192 191 192 192 193 196 199 198 200 200 200 201 200 199]]

在此处输入图像描述 .

原文由 Prof.Plague 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你可以使用 PIL。应该没问题。我有 RGB 图像并转换它们:

 from PIL import Image
img = Image.open("image_file_path") #for example image size : 28x28x3
img1 = img.convert('L')  #convert a gray scale
print(img1.size)
>> (28,28)

但是图像没有通道

y = np.expand_dims(img1, axis=-1)
print(y.shape)
>> (28,28,1)

原文由 Bahadir 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题