OpenCV - 读取带有 alpha 通道的灰度或单色图像

6

更新于2018年10月13日

这个问题已经在OpenCV 3.4中得到修复。

import cv2
import numpy as np
image = cv2.imread('1.png', cv2.IMREAD_UNCHANGED)

image.shape
>> (480, 960, 4)

np.sum(img[:,:,:3])
>> 0

np.mean(img[:,:,3])
>> 37.929637586805555

这里有一个类似的问题,但是没有得到回答 here

我该如何在OpenCV中读取带有alpha通道的灰度图像?例如,如果我尝试读取以下图像,我只会得到一个全为零的二维数组。

enter image description here

image = cv2.imread('1.png', cv2.IMREAD_UNCHANGED)
image.shape

(480, 960)

我观察到相同的行为(OpenCV3.1)。这似乎是一个错误。 - John1024
是的,我也在使用OpenCV 3.1(和Python 3.5)。 - kampta
我猜你的图片出了问题。我试着在GIMP中对它进行分解,但失败了。 - ZdaR
它在Ubuntu上的ImageViewer和ImageMagick上打开得很好,你遇到了什么错误? - kampta
它能够正确地打开,但我无法在GIMP中将它分解为RGBA组件。 - ZdaR
1
好的 :),我猜这不是图像的问题,但那确实是问题所在。如果可能的话,如何使用OpenCV将其分解为RGBA组件? - kampta
1个回答

2
在OpenCV 3.4.2版本中,该错误已得到解决(可能在早期版本中也有,但未在3.1.0中修复)。
如何检查:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace std;

int main( int argc, char** argv )
{
    const char* imagePath = "grayscale_with_alpha.png";

    cout << "OpenCV version : " << CV_VERSION << endl;

    cv::Mat image;
    image = cv::imread(imagePath, cv::IMREAD_UNCHANGED);   // Read the file

    if(!image.data )                              // Check for invalid input
    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }

    vector<int> params;
    try 
    {
        cv::imwrite("grayscale_with_alpha_out.png", image, params);
    }
    catch (runtime_error& ex) {
        fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
        return 1;
    }


    return 0;
}

构建和运行:

> g++ -lopencv_core -lopencv_highgui -lopencv_imgcodecs -o main main.cpp
> ./main
> OpenCV version : 3.4.2

图像“grayscale_with_alpha_out.png”必须与输入图像相同。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接