OpenCV - 使用Alpha通道

时间:2016-09-15 04:39:22

标签: python image opencv image-processing alpha

更新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

如何使用Alpha通道在OpenCV中读取灰度图像?例如,如果我尝试读取下面的图像,我得到的是全部为零的2d数组。

enter image description here

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

(480, 960)

1 个答案:

答案 0 :(得分:1)

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