OpenCV-创建颜色蒙版

时间:2019-03-01 08:27:37

标签: c# python c++ windows opencv

朋友!有两个输入图像。一个背景图像,另一个蒙版图像。我需要得到面膜的彩色部分。

我需要得到什么: backgroundmaskresult image

但是我得到了完全不同的东西:backgroundmaskresult image

我的代码在C#中:

 //Read files
Mat img1 = CvInvoke.Imread(Environment.CurrentDirectory + "\\Test\\All1.jpg");
Mat img = CvInvoke.Imread(Environment.CurrentDirectory + "\\Test\\OriginalMask.jpg");

// Threshold and MedianBlur mask
CvInvoke.Threshold(img, img, 0, 255, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
CvInvoke.MedianBlur(img, img, 13);

// without this conversion, an error appears: (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1)
CvInvoke.CvtColor(img, img, Emgu.CV.CvEnum.ColorConversion.Rgb2Gray);

CvInvoke.BitwiseNot(img1, img1, img);

//Save file
img1.Save(Environment.CurrentDirectory + "\\Test\\Result.jpg");

第一个问题:如何获得图片中显示的结果?

第二个问题:如果不转换掩码,为什么会出现错误:(mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1)

第三个问题:如何在最终图像中制作透明背景而不是白色背景?

解决方案不必在C#中。该解决方案适用于任何编程语言,因为语法OpenCV大致相同。预先谢谢你。

3 个答案:

答案 0 :(得分:3)

由于我最熟悉C ++,因此我将在答案中使用C ++。

这是我的建议:

// Load background as color image.
cv::Mat background = cv::imread("background.jpg", cv::IMREAD_COLOR);

// Load mask image as grayscale image.
cv::Mat mask = cv::imread("mask.jpg", cv::IMREAD_GRAYSCALE);

// Start time measurement.
auto start = std::chrono::system_clock::now();

// There are some artifacts in the JPG...
cv::threshold(mask, mask, 128, 255, cv::THRESH_BINARY);

// Initialize result image.
cv::Mat result = background.clone().setTo(cv::Scalar(255, 255, 255));

// Copy pixels from background to result image, where pixel in mask is 0.
for (int x = 0; x < background.size().width; x++)
    for (int y = 0; y < background.size().height; y++)
        if (mask.at<uint8_t>(y, x) == 0)
            result.at<cv::Vec3b>(y, x) = background.at<cv::Vec3b>(y, x);

// End time measurement.
auto end = std::chrono::system_clock::now();

// Output duration duration.
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << elapsed_seconds.count() << "\n";

// Write result.
cv::imwrite("result.png", result);

// Start time measurement.
start = std::chrono::system_clock::now();

// Generate new image with alpha channel.
cv::Mat resultTransparent = cv::Mat(result.size(), CV_8UC4);

// Copy pixels in BGR channels from result to transparent result image.
// Where pixel in mask is not 0, set alpha to 0.
for (int x = 0; x < background.size().width; x++)
{
    for (int y = 0; y < background.size().height; y++)
    {
        resultTransparent.at<cv::Vec4b>(y, x)[0] = result.at<cv::Vec3b>(y, x)[0];
        resultTransparent.at<cv::Vec4b>(y, x)[1] = result.at<cv::Vec3b>(y, x)[1];
        resultTransparent.at<cv::Vec4b>(y, x)[2] = result.at<cv::Vec3b>(y, x)[2];

        if (mask.at<uint8_t>(y, x) != 0)
            resultTransparent.at<cv::Vec4b>(y, x)[3] = 0;
        else
            resultTransparent.at<cv::Vec4b>(y, x)[3] = 255;
    }
}

// End time measurement.
end = std::chrono::system_clock::now();

// Output duration duration.
elapsed_seconds = end - start;
std::cout << elapsed_seconds.count() << "\n";

// Write transparent result.
cv::imwrite("resultTransparent.png", resultTransparent);

这两个输出的结果(在白色StackOverflow背景上,您不会在第二张图像上看到透明性):

White background

Transparent background

答案 1 :(得分:1)

只需在HanseHirse的答案中添加一个小细节:

如果您向蒙版添加高斯模糊(就像您在问题中使用CvInvoke.MedianBlur(img, img, 13);所做的那样),则蒙版的边缘将更平滑,并且将输出图像放在另一个图像上时看起来会更好。 / p>

您只需将输出图像的第四个通道直接设置为模糊蒙版即可。

所以不是

if (mask.at<uint8_t>(y, x) != 0)
            resultTransparent.at<cv::Vec4b>(y, x)[3] = 0;
        else
            resultTransparent.at<cv::Vec4b>(y, x)[3] = 255;

您可以尝试

resultTransparent.at<cv::Vec4b>(y, x)[3] = mask.at<uint8_t>(y, x);

答案 2 :(得分:1)

如果可以激发您的灵感,那么在Python中获得相同的结果:

import cv2
import numpy as np
# Read files
img1 = cv2.imread("All1.jpg",cv2.IMREAD_COLOR);
img = cv2.imread("OriginalMask.jpg",cv2.IMREAD_GRAYSCALE)  # loading in grayscale

# Threshold and MedianBlur mask
_, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)  # corrected to 127 instead of 0
img = cv2.medianBlur(img, 13)

# fill with white
dest= np.full(np.shape(img1),255,np.uint8)

# Assuming dst and src are of same sizes
# only copy values where the mask has color > 0
dest[img>0] = img1[img>0]  # after @T.Kau's suggestion


cv2.imshow('dest',dest)
cv2.waitKey(0)
cv2.destroyAllWindows()