Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,将3通道rgb彩色图像更改为1通道灰色的速度有多快?_Python_Python 3.x_Image Processing - Fatal编程技术网

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

在Python中,将3通道rgb彩色图像更改为1通道灰色的速度有多快?,python,python-3.x,image-processing,Python,Python 3.x,Image Processing,我在4D阵列中有近40000张图像,其中包含原始像素数据(示例数、宽度、高度、通道)。每个图像的宽度为32像素,高度为32像素,RGB颜色有3个通道。我想将它们更改为灰度图像(从3个rgb通道获得1个强度)。我怎么能做得很快呢? 我的代码: 结果: X_序列_灰度图像数据形状=(40000,32,32,3) X_序列_灰度图像数据形状=(40000,32,32,1) 这很好,但要花很多时间 我还尝试使用cv2: X_train_gray = X_train[0].copy() print("X_

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

结果:
X_序列_灰度图像数据形状=(40000,32,32,3)
X_序列_灰度图像数据形状=(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\u序列\u灰度图像数据形状=(32,32,3)
X\u序列\u灰度图像数据形状=(32,32)
但我失去了强度,不知道如何获得它。
那么,如何快速地将此图像从3通道rgb更改为1通道灰度?

尝试使用:

cv::cvtColor(gray_img,color_img,CV_GRAY2BGR)

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

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 196 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 201 200 199]]


如果您可以使用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)
y = np.expand_dims(img1, axis=-1)
print(y.shape)
>> (28,28,1)