2014-01-06 51 views
2

我需要在實時相機饋送上繪製透明圖像。下面是在相機饋送上顯示爲覆蓋的png文件。如何在opencv上通過實時相機饋送繪製透明圖像

Circle image as overlay over the camera window

的下面是一段代碼從相機獲取的幀,並顯示在屏幕上。我也試圖把這個圓畫成疊加圖,但圓不透明。我認爲是錯誤的或錯過了下面的一段代碼?

#include "opencv2/highgui/highgui.hpp" 
#include "opencv2/imgproc/imgproc.hpp" 
#include <iostream> 
#include <stdio.h> 
#include <stdlib.h> 

using namespace cv; 
using namespace std; 

int main() { 

Mat src; 
Mat overlay = imread ("circle.png", -1); 

VideoCapture cap (0); 

while (1) { 

cap >> src; 
cvtColor(src, src, CV_BGR2BGRA); 
overlay.copyTo(src.colRange(0,400).rowRange(0,400)); 
imshow ("src",src); 
waitKey(10); 

} 

return 0; 
} 
+0

哎,那也不會那麼容易了。爲什麼不只是畫一個[ellipse](http://docs.opencv.org/modules/core/doc/drawing_functions.html#ellipse)呢? – berak

+0

確保該圓圈的白色區域具有適當的alpha通道(值爲255)。還要在waitKey附近添加if&break語句。 – baci

+0

@berak它只是一個例子..我需要在cmara feed而不是橢圓上繪製另一個圖像。 – user2727765

回答

2

如果疊加圖像有alpha通道(並假設圖像大小相同的),你可以做這樣的事情

cv::Mat display_img(src.size(), src.type()); 
for (int y = 0; y < src.rows; y++) 
{ 
    const cv::Vec3b* src_pixel = src.ptr<cv::Vec3b>(y); 
    const cv::Vec4b* ovl_pixel = overlay.ptr<cv::Vec4b>(y); 
    cv::Vec3b* dst_pixel = display_img.ptr<cv::Vec3b>(y); 
    for (int x = 0; x < src.cols; x++, ++src_pixel, ++ovl_pixel, ++dst_pixel) 
    { 
     double alpha = (*ovl_pixel).val[3]/255.0; 
     for (int c = 0; c < 3; c++) 
     { 
      (*dst_pixel).val[c] = (uchar) ((*ovl_pixel).val[c] * alpha + (*src_pixel).val[c] * (1.0 -alpha)); 
     } 
    } 
} 
+3

This works http://jepsonsblog.blogspot.in/2012/10/overlay-透明圖像合opencv.html – user2727765

2

我只是解決了完全相同的問題,我的解決辦法找出疊加層中的哪些像素具有某些內容,並將圖像中的像素歸零。現在您知道兩個圖像中的一箇中的每個像素都爲零,那麼您可以將這兩個圖像一起添加。

在python:

import numpy as np 
import cv2 

# load the overlay file 
overlay = cv2.imread('overlay.png') 

# detect which pixels in the overlay have something in them 
# and make a binary mask out of it 
overlayMask = cv2.cvtColor(overlay, cv2.COLOR_BGR2GRAY) 
res, overlayMask = cv2.threshold(overlayMask, 10, 1, cv2.THRESH_BINARY_INV) 

# expand the mask from 1-channel to 3-channel 
h,w = overlayMask.shape 
overlayMask = np.repeat(overlayMask, 3).reshape((h,w,3)) 


# here's where the work gets done : 

# mask out the pixels that you want to overlay 
img *= overlayMask 

# put the overlay on 
img += overlay 

# Show the image. 
cv2.imshow(WINDOW_NAME, img)