简体   繁体   English

如何使用 opencv 将图像用作图案填充

[英]How to use image as a pattern fill using opencv

I want to fill a contour with an image thumbnail.The area contour will have different shapes.我想用图像缩略图填充轮廓。区域轮廓将具有不同的形状。 I need to read a thumbnail image as a pattern and to fill the contour with this image.我需要将缩略图作为图案读取并用该图像填充轮廓。 For example例如在此处输入图片说明 在此处输入图片说明

I prefer to a solution using opencv.我更喜欢使用 opencv 的解决方案。 But any programmatic approach is appreciable.但任何程序化方法都是可观的。

This is an OpenCV solution.这是一个 OpenCV 解决方案。 The essential parts are:主要部分是:

  • repeat function to create the pattern 重复功能以创建模式
  • copyTo with a mask to get the final result. copyTo带有掩码以获得最终结果。

This is a sample code:这是一个示例代码:

#include <opencv2\opencv.hpp>
using namespace cv;

int main()
{
    // Template image
    Mat3b img = imread("path_to_image");

    // Create a circular mask
    Mat1b mask(1000, 1000, uchar(0));
    circle(mask, Point(500, 500), 500, Scalar(255), CV_FILLED);

    // Or load your own mask
    //Mat1b mask = imread("path_to_mask", IMREAD_GRAYSCALE)

    // Compute number of repetition in x and y
    int nx = (mask.cols / img.cols) + 1;
    int ny = (mask.rows / img.rows) + 1;

    // Create repeated pattern
    Mat3b repeated = repeat(img, ny, nx);

    // Crop to meet mask size
    Mat3b crop = repeated(Rect(0, 0, mask.cols, mask.rows));

    // Create a white image same size as mask
    Mat3b result(mask.rows, mask.cols, Vec3b(255, 255, 255));

    // Copy pattern with the mask
    crop.copyTo(result, mask);

    return 0;
}

that will produce as result : result会产生:

在此处输入图片说明

Not sure what you mean by a "contour" , but you can fill a transparent area with ImageMagick like this:不确定“轮廓”是什么意思,但您可以像这样用 ImageMagick 填充透明区域:

First, make a circular mask:首先,制作一个圆形面具:

convert -size 500x500 xc:black -fill white -draw "circle 250,250 250,500" -colorspace gray PNG8:mask.png

在此处输入图片说明

Now tile a pattern inside the mask:现在在蒙版内平铺一个图案:

convert -size 500x500 tile:tomato.png mask.png -compose copyopacity -composite result.png

在此处输入图片说明

Oh, you can also create a pattern to use as the fill while drawing directly:哦,你也可以在直接绘制时创建一个用作填充的图案:

convert -size 500x500 xc:white -fill tile:tomato.png -draw "circle 250,250 250,500" result.png

在此处输入图片说明

In case a contour is a vector path outline, you can also do this:如果轮廓是矢量路径轮廓,您也可以这样做:

convert -size 100x100 xc:black \
  -stroke yellow -strokewidth 2 -fill tile:smalltom.png \
  -draw 'path "M 10 50 A 40 40 0 0 1 50 10 L 50 20 A 30 30 0 0 0 20 50 Z"' \
 result.png

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM