如何使用NumPy处理彩色和灰度图像?

2024-10-03 17:28:08 发布

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

我使用的人脸检测算法MTCNN需要NumPy,当我试图读取灰度图像时,NumPy抛出了一个错误。错误源于在尝试处理灰度图像时调用NumPy的转置函数,将(0、2、1、3)作为轴。在彩色图像上使用相同的轴调用相同的函数,它们工作正常,只有在图像为灰度时才会中断

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

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

除了从数据集中删除所有灰度图像之外,我还有什么办法可以避免这种情况


Tags: inpy图像imglibpackagessiteresult
1条回答
网友
1楼 · 发布于 2024-10-03 17:28:08

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

我假设您有一个[N, H, W, c]形状,表示大小为H x Wc彩色通道的N图像。然后调用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)

相关问题 更多 >