簡體   English   中英

如何加載具有 4 個通道的 png 圖像?

[英]How to load png images with 4 channels?

我一直在嘗試使用透明通道(RGB 和 Alph)加載 .png 文件,但沒有成功。 看起來 openCV 從圖像中剝離了第 4 個通道。 即使我必須修改 OpenCV 源代碼並重建它,是否有任何方法可以加載包含 alpha 通道的完整 4 個通道的圖像?

如果你正在使用OpenCV的2或3的OpenCV你應該使用IMREAD_ *標志(截至提到 這里)。

C++

using namespace cv;
Mat image = imread("image.png", IMREAD_UNCHANGED);

蟒蛇

import cv2
im = cv2.imread("image.png", cv2.IMREAD_UNCHANGED)

根據文檔,OpenCV 支持 PNG 上的 alpha 通道。

只需使用 CV_LOAD_IMAGE_UNCHANGED 作為標志調用 imread 函數,如下所示:

cvLoadImage("file.png", CV_LOAD_IMAGE_UNCHANGED)

讀取透明 PNG 的正確方法是使用第 4 個通道作為 alpha 通道。 大多數時候人們想要白色背景,如果是這種情況,那么下面的代碼可用於 alpha 合成。

def read_transparent_png(filename):
    image_4channel = cv2.imread(filename, cv2.IMREAD_UNCHANGED)
    alpha_channel = image_4channel[:,:,3]
    rgb_channels = image_4channel[:,:,:3]

    # White Background Image
    white_background_image = np.ones_like(rgb_channels, dtype=np.uint8) * 255

    # Alpha factor
    alpha_factor = alpha_channel[:,:,np.newaxis].astype(np.float32) / 255.0
    alpha_factor = np.concatenate((alpha_factor,alpha_factor,alpha_factor), axis=2)

    # Transparent Image Rendered on White Background
    base = rgb_channels.astype(np.float32) * alpha_factor
    white = white_background_image.astype(np.float32) * (1 - alpha_factor)
    final_image = base + white
    return final_image.astype(np.uint8)

關於此的詳細博客在這里

如果您想在另一個圖像上繪制此透明圖像,請按照@satya-mallick(模式 IMREAD_UNCHANGED)的回答打開您的圖像,然后使用此方法在框架 Mat 上繪制圖像:

/**
 * @brief Draws a transparent image over a frame Mat.
 * 
 * @param frame the frame where the transparent image will be drawn
 * @param transp the Mat image with transparency, read from a PNG image, with the IMREAD_UNCHANGED flag
 * @param xPos x position of the frame image where the image will start.
 * @param yPos y position of the frame image where the image will start.
 */
void drawTransparency(Mat frame, Mat transp, int xPos, int yPos) {
    Mat mask;
    vector<Mat> layers;
    
    split(transp, layers); // seperate channels
    Mat rgb[3] = { layers[0],layers[1],layers[2] };
    mask = layers[3]; // png's alpha channel used as mask
    merge(rgb, 3, transp);  // put together the RGB channels, now transp insn't transparent 
    transp.copyTo(frame.rowRange(yPos, yPos + transp.rows).colRange(xPos, xPos + transp.cols), mask);
}

加載具有所有 4 個通道的 png 圖像的最佳方法是;

img= cv2.imread('imagepath.jpg',negative value)

根據 openCV 文檔,
如果 Flag 值是,
1) =0 返回灰度圖像。
2) <0 按原樣返回加載的圖像(帶有 alpha 通道)。

您可以使用:

import matplotlib.image as mpimg


img=mpimg.imread('image.png')
plt.imshow(img)

在我的例子中,是文件擴展名導致了問題。 檢查您的 png 是 png 還是其他東西;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM