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

OpenCV - Read a gray scale or monochrome image with alpha channel

更新 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 通道读取灰度图像?例如,如果我尝试读取下图,我得到的只是全零的二维数组。

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

(480, 960)

在 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"必须与输入图片相同。