如何在C++中用文字制作图片的白色背景

Posted

技术标签:

【中文标题】如何在C++中用文字制作图片的白色背景【英文标题】:How can make white background of the picture with texts in C++ 【发布时间】:2021-04-26 14:02:15 【问题描述】:

我想裁剪 1280x720 图像上的文本并将文本放回 1280x720 白色图像上。我希望文字之外的地方是白色的。

其实我把图片中的所有文字都剪掉了拼贴,但是文字的大小变了,我不要这个。

我希望图片中文字的位置和大小不要改变。

如何在 Opencv 中做到这一点? c++ 或 python

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/opencv_modules.hpp>

#include <cmath>
#include <fstream>

using namespace std;
using namespace cv;

Mat detect_text(Mat input) 
    Mat large = input;
    Mat rgb;
    // downsample and use it for processing
    pyrDown(large, rgb);
    Mat small;
    cvtColor(rgb, small, COLOR_BGR2GRAY);
    // morphological gradient
    Mat grad;
    Mat morphKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
    morphologyEx(small, grad, MORPH_GRADIENT, morphKernel);
    // binarize
    Mat bw;
    threshold(grad, bw, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
    // connect horizontally oriented regions
    Mat connected;
    morphKernel = getStructuringElement(MORPH_RECT, Size(9, 1));
    morphologyEx(bw, connected, MORPH_CLOSE, morphKernel);
    // find contours
    Mat mask = Mat::zeros(bw.size(), CV_8UC1);
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    findContours(connected, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE,
                 Point(0, 0));
    // filter contours
    cv::Mat croppedImage;

    Mat temp_Image(input.size(), CV_8UC3, Scalar(255, 255, 255));

    for(int idx = 0; idx >= 0; idx = hierarchy[idx][0]) 
        Rect rect = boundingRect(contours[idx]);
        Mat maskROI(mask, rect);

        maskROI = Scalar(0, 0, 0);
        // fill the contour
        drawContours(mask, contours, idx, Scalar(255, 255, 255), FILLED);
        // ratio of non-zero pixels in the filled region
        double r = (double)countNonZero(maskROI) / (rect.width * rect.height);

        // assume at least 45% of the area is filled if it contains text
        if(r > 0.45 &&
           (rect.height > 8 && rect.width > 8) // constraints on region size
           // these two conditions alone are not very robust. better to use
           // something
           // like the number of significant peaks in a horizontal projection as a
           // third condition
        ) 
            rect.x = rect.x;
            rect.y = rect.y;
            rect.height = rect.height + 10;
            rect.width = rect.width + 10;

            rectangle(rgb, rect, Scalar(0, 255, 0), 2);
            croppedImage = rgb(rect);

            //
            //  to put cropped texts in tem_image
            //
            // imwrite(string("test_text_contours.jpg"), temp_image);
        
    
    // imwrite(string("test_text_contours.jpg"), croppedImage);

    return croppedImage;


int main(int argc, char *argv[])

    Mat img = cv.imread("1.jpg");
    detect_text(img);
    return 0;

【问题讨论】:

【参考方案1】:

这里是python代码:

import cv2
import numpy as np

def get_white_image(img, crops):
    image_sizey, image_sizex, c = img.shape
    white_image = np.zeros([image_sizey, image_sizex, 3], dtype=np.uint8)
    white_image.fill(255)
    for crop in crops:
        white_image[crop[0]:crop[1], crop[2]:crop[3]] = img[crop[0]:crop[1], crop[2]:crop[3]]
    return white_image


image = cv2.imread("baldo.jpg")
cv2.imshow("image", image)
crops = []
crops.append([35, 80, 70, 140])
crops.append([85, 95, 50, 160])
crops.append([115, 145, 50, 90])
crops.append([220, 240, 80, 125])
result = get_white_image(image, crops=crops)
cv2.imshow("result", result)
cv2.waitKey(0)

结果如下: Image and white image

【讨论】:

以上是关于如何在C++中用文字制作图片的白色背景的主要内容,如果未能解决你的问题,请参考以下文章

怎么制作ICO图标使背景颜色为透明?

怎么制作透明图片,

[html语言]网页制作/如何在已切片图片的某一固定区域上,让图片和文字从下至上滚动?

Unity制作提示功能,背景图片自适应文字大小

如何在LaTeX中制作这样的插图,图片+文字?

手机上有啥可以自己制作文字图片的软件?