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

2024-06-12 02:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个4D数组中有将近40000个图像,其中包含原始像素数据(示例数、宽度、高度、通道数)。每幅图像的宽度为32像素,高度为32像素,RGB颜色有3个通道。我想将它们更改为灰度图像(从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_灰度图像数据形状=(40000、32、32、3)
X_train_灰度图像数据形状=(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_灰度图像数据形状=(32,32,3)
X_train_灰度图像数据形状=(32,32)
但我失去了强度,不知道如何获得它。
那么,如何快速地将这些图像从3通道rgb更改为1通道灰度呢?


Tags: 数据in图像imagefordatatrainrgb
3条回答

尝试使用:

cv::cvtColor(gray_img,color_img,CV_GRAY2BGR)

如果你能用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)

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

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]]

enter image description here

相关问题 更多 >