影像如下,我希望所有黑色像素都是透明的并將其保存為 png 檔案。

uj5u.com熱心網友回復:
你可以像這樣快速和矢量化:
import cv2
import numpy as np
# Load image as Numpy array in BGR order
na = cv2.imread('I5jKW.png')
# Make a True/False mask of pixels whose BGR values sum to more than zero
alpha = np.sum(na, axis=-1) > 0
# Convert True/False to 0/255 and change type to "uint8" to match "na"
alpha = np.uint8(alpha * 255)
# Stack new alpha layer with existing image to go from BGR to BGRA, i.e. 3 channels to 4 channels
res = np.dstack((na, alpha))
# Save result
cv2.imwrite('result.png', res)

筆記:
1 你可以同樣使用cv2.merge()代替,np.dstack()它可能更快。
2 您同樣可以使用 PIL/Pillow 代替 OpenCV 函式來讀取/保存影像。
uj5u.com熱心網友回復:
根據
由于我對python不熟悉,所以我用C 撰寫了步驟。對不起。
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
int main()
{
cv::Mat img = cv::imread("/ur/input/img.png",cv::IMREAD_COLOR);
cv::Mat mask = cv::Mat::zeros(cv::Size(img.cols,img.rows),CV_8UC4);
cv::namedWindow("Input",0);
cv::namedWindow("Output",0);
for(int i=0; i<mask.cols; i )
{
for(int j=0; j<mask.rows; j )
{
if(img.at<cv::Vec3b>(cv::Point(i,j))[0] == 0 &&
img.at<cv::Vec3b>(cv::Point(i,j))[1] == 0 &&
img.at<cv::Vec3b>(cv::Point(i,j))[2] == 0)
{
mask.at<cv::Vec4b>(cv::Point(i,j))[0] = img.at<cv::Vec3b>(cv::Point(i,j))[0];
mask.at<cv::Vec4b>(cv::Point(i,j))[1] = img.at<cv::Vec3b>(cv::Point(i,j))[1];
mask.at<cv::Vec4b>(cv::Point(i,j))[2] = img.at<cv::Vec3b>(cv::Point(i,j))[2];
mask.at<cv::Vec4b>(cv::Point(i,j))[3] = 0;
}
else {
mask.at<cv::Vec4b>(cv::Point(i,j))[0] = img.at<cv::Vec3b>(cv::Point(i,j))[0];
mask.at<cv::Vec4b>(cv::Point(i,j))[1] = img.at<cv::Vec3b>(cv::Point(i,j))[1];
mask.at<cv::Vec4b>(cv::Point(i,j))[2] = img.at<cv::Vec3b>(cv::Point(i,j))[2];
mask.at<cv::Vec4b>(cv::Point(i,j))[3] = 255;
}
}
}
cv::imshow("Input",img);
cv::imshow("Output",mask);
cv::imwrite("/ur/writing/dir/transparent.png",mask);
cv::waitKey(0);
return 0;
}
uj5u.com熱心網友回復:
這是在 Python/OpenCV/Numpy 中執行此操作的另一種方法。
import cv2
import numpy as np
# load image
img = cv2.imread('girl_on_black.png')
# threshold on black to make a mask
color = (0,0,0)
mask = np.where((img==color).all(axis=2), 0, 255).astype(np.uint8)
# put mask into alpha channel
result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:, :, 3] = mask
# save resulting masked image
cv2.imwrite('girl_on_black_transparent.png', result)
# display result, though it won't show transparency
cv2.imshow("MASK", mask)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/373628.html
