【问题标题】:How can I use NumPy to work with both colored and grayscale images?如何使用 NumPy 处理彩色和灰度图像?
【发布时间】:2021-08-19 04:09:01
【问题描述】:

我正在使用需要 NumPy 的人脸检测算法 MTCNN,当我尝试读取灰度图像时,NumPy 会引发错误。该错误来自在尝试处理灰度图像时以 (0, 2, 1, 3) 作为轴调用 NumPy 的 Transpose 函数。在彩色图像上使用相同的轴调用相同的函数,它们工作得很好,只有在图像为灰度时才会中断。

以下是我正在使用的代码的简短说明:

from matplotlib import pyplot
from mtcnn.mtcnn import MTCNN
import cv2

for filename in os.listdir("E:\\UTKFace"):
    name_path = "E:\\UTKFace\\" + filename
    pixels = pyplot.imread(name_path)
    faces = detector.detect_faces(pixels)

这适用于彩色图像,但是当循环到达灰度图像时,我会收到此错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-81451c75694c> in <module>
     55 
     56     # detect faces in the image
---> 57     faces = detector.detect_faces(pixels)
     58     if (len(faces)):
     59         count_positive = count_positive + 1

~\Anaconda3\envs\ambiente\lib\site-packages\mtcnn\mtcnn.py in detect_faces(self, img)
    306         # We pipe here each of the stages
    307         for stage in stages:
--> 308             result = stage(img, result[0], result[1])
    309 
    310         [total_boxes, points] = result

~\Anaconda3\envs\ambiente\lib\site-packages\mtcnn\mtcnn.py in __stage1(self, image, scales, stage_status)
    344 
    345             img_x = np.expand_dims(scaled_image, 0)
--> 346             img_y = np.transpose(img_x, (0, 2, 1, 3))
    347 
    348             out = self._pnet.predict(img_y)

<__array_function__ internals> in transpose(*args, **kwargs)

~\Anaconda3\envs\ambiente\lib\site-packages\numpy\core\fromnumeric.py in transpose(a, axes)
    651 
    652     
--> 653     return _wrapfunc(a, 'transpose', axes)
    654 
    655 

~\Anaconda3\envs\ambiente\lib\site-packages\numpy\core\fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     56 
     57     try:
---> 58         return bound(*args, **kwds)
     59     except TypeError:
     60         # A TypeError occurs if the object does have such a method in its

ValueError: axes don't match array

除了从数据集中删除所有灰度图像之外,我还有哪些选择可以规避这个问题?

【问题讨论】:

    标签: python numpy deep-learning transpose face-detection


    【解决方案1】:

    您可以在numpy.transpose 中指定axes 参数

    我想你有一个[N, H, W, c] 形状,代表N 大小为H x Wc 颜色通道的图像。然后你会调用data.transpose([0, 2, 1, 3]) 产生一个[N, W, H, c] 数组。如果你省略它会产生一个[c, W, H, N] 数组,如果N != c 它可能会破坏你的程序,否则它会工作但会给出毫无意义的结果。

    也许您的数组用于灰度图像的形状为[N, H, W] 而不是[N, H, W, 1]

    您可以使用data.reshape(*data.shape[:3], -1])data[:,:,:,None] 来确保它有4 个维度。

    如果您有一个 [N, H, W, 1] 数组并且您想将其设为 [N, H, W, 3] 你可以使用data.repeat(3, axis=3)

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 2013-01-20
      • 2015-11-20
      • 2022-01-12
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      相关资源
      最近更新 更多