所以我试图加载图像并将其放在我的脸上,但问题是图像仅作为 RBG 读取,没有 (A) 透明度值。阅读文档表明 copyTo 函数不支持透明度 文档建议我应该加载未更改标志的图像以确保 Alpha 通道可用,但是当我这样做时,它崩溃了。
其他文档建议我需要制作一个 alpha 蒙版并用这个蒙版覆盖图像。
这是我的代码:
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
int main(int argc, char** argv)
{
// Load the video source
cv::VideoCapture cap(0);
// Load the eye image
cv::Mat eye = cv::imread("eye.png"); // cv::IMREAD_UNCHANGED - Crash if this flag is set.
// Create a window to display the output
cv::namedWindow("Replace Eyes", cv::WINDOW_NORMAL);
while (true)
{
cv::Mat frame;
cap >> frame;
// Convert the frame to grayscale
cv::Mat gray;
cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY);
// Detect faces in the grayscale frame
std::vector<cv::Rect> faces;
cv::CascadeClassifier face_cascade("haarcascade_frontalface_default.xml");
face_cascade.detectMultiScale(gray, faces, 1.1, 3, 0, cv::Size(100, 100));
// Detect eyes in the face region
std::vector<cv::Rect> eyes;
cv::CascadeClassifier eye_cascade("haarcascade_eye.xml");
for (const cv::Rect& face : faces)
{
// Crop the face region from the frame
cv::Mat face_roi = frame(face);
eye_cascade.detectMultiScale(face_roi, eyes, 1.1, 3, 0, cv::Size(30, 30));
// Loop over each detected eye
for (const cv::Rect& eye_roi : eyes)
{
// Resize the eye image to fit the eye region
cv::Mat eye_resized;
cv::resize(eye, eye_resized, eye_roi.size());
// Replace the eye region with the eye image
eye_resized.copyTo(face_roi(eye_roi));
}
}
cv::imshow("Test Window", frame);
if (cv::waitKey(30) == 'q' )
{
break;
}
}
cap.release();
cv::destroyAllWindows();
return 0;
}
谢谢!