【问题标题】:Converting Color Images to Grayscale but shape of the image stays identical将彩色图像转换为灰度,但图像的形状保持不变
【发布时间】:2021-10-29 05:21:49
【问题描述】:

我已将一些图像从 RGB 转换为灰度以用于机器学习。 但是转换后的灰度图的形状还是3,和彩色图一样。

转换代码:

from PIL import Image
img = Image.open('path/to/color/image')
imgGray = img.convert('L')
imgGray.save('path/to/grayscale/image')

检查图像形状的代码:

import cv2
im_color = cv2.imread('path/to/color/image')
print(im_color.shape)
im_gray2 = cv2.imread('path/to/grayscale/image')
print(im_gray2.shape)

【问题讨论】:

  • 使用 skimage 库。函数:rgb2gray()。您将获得单层灰度图像作为输出。只需确保将 RGB 图像作为 numpy ndarray 即可。
  • 你为什么要使用 PIL 和 OpenCV - 你很少需要两者,而且它往往会导致混乱。

标签: python image image-processing python-imaging-library cv2


【解决方案1】:

你做到了

im_gray2 = cv2.imread('path/to/grayscale/image')

OpenCV 不检查图像的颜色 - 它确实假设图像是彩色的并且所需的输出是 BGR 8 位格式。您需要通知 OpenCV 您希望输出为灰度(2D 强度数组),如下所示

im_gray2 = cv2.imread('path/to/grayscale/image', cv2.IMREAD_GRAYSCALE)

如果您想了解更多关于阅读图像的信息,请阅读OpenCV: Getting Started with Images

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2016-01-11
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    相关资源
    最近更新 更多