UPDATE 2018-10-13
This issue has been fixed in 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
A similar question has been asked but unanswered here.
How can I read a gray scale image in OpenCV with alpha channel? For example, if I try to read the following image, all I get is 2d array of all zeros.
image = cv2.imread('1.png', cv2.IMREAD_UNCHANGED)
image.shape
(480, 960)
In OpenCV version 3.4.2 this bug solved (may be in earlier versions too but not fixed in 3.1.0)
How to check:
#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;
}
Build and run:
> g++ -lopencv_core -lopencv_highgui -lopencv_imgcodecs -o main main.cpp
> ./main
> OpenCV version : 3.4.2
Image "grayscale_with_alpha_out.png" must be same as input image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With