kam*_*pta 5 python opencv alpha image image-processing
更新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
Run Code Online (Sandbox Code Playgroud)
有人问过类似的问题,但这里没有答案.
如何在带有Alpha通道的OpenCV中读取灰度图像?例如,如果我尝试读取下面的图像,我得到的是全部为零的2d数组.
image = cv2.imread('1.png', cv2.IMREAD_UNCHANGED)
image.shape
(480, 960)
Run Code Online (Sandbox Code Playgroud)
在 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;
}
Run Code Online (Sandbox Code Playgroud)
构建并运行:
> g++ -lopencv_core -lopencv_highgui -lopencv_imgcodecs -o main main.cpp
> ./main
> OpenCV version : 3.4.2
Run Code Online (Sandbox Code Playgroud)
图像“grayscale_with_alpha_out.png”必须与输入图像相同。