美文网首页
opencv在图片中输入字符

opencv在图片中输入字符

作者: 此间不留白 | 来源:发表于2020-12-21 15:15 被阅读0次

    《learning opencv》第6章第2题解决方案

    前言

    opencv提供了方便的函数,用以处理在图像上输出字符的问题,而且支持多种字体的输出。但是opencv提供的功能只支持英文字符的输出,无法解决中文输出的问题。对于中文字符的输出,通过第三方提供的函数可以解决,本篇文章将会详细介绍了英文输出和中文输出。

    有如下所示的图片:



    实现以下功能:

    • 将原始图像转换为三个通道的灰度图片(即是一个三通道图像,但视觉现象还是灰度图像)
    • 在灰度图像中输出彩色的英文字符

    在灰度图像中输出字符(串),主要通过cv::putText()函数,实现,该函数的详细介绍如下:

    void putText( InputOutputArray img, const String& text, Point org,
                             int fontFace, double fontScale, Scalar color,
                             int thickness = 1, int lineType = LINE_8,
                             bool bottomLeftOrigin = false )
    @param InputOutputArray img 字符输出的源图像
    @param const String& text 输出字符串
    @param Point org 输出字符串在图像中的位置
    @param int fontFace 输出字符串的字体
    @param double fontScale 输出字符串的大小
    @param bool bottomLeftOrigin 如果为真,二维图像起点坐标以左下角,否则,为左上角
    

    综上,在图像上实现字符串输出的代码如下:

    Mat m = imread("timg.jpg");
    Mat m2gray, gray2m;
    cvtColor(m, m2gray, COLOR_BGR2GRAY);
    cvtColor(m2gray, gray2m, COLOR_GRAY2BGR);
    putText(gray2m,"Hello world",Point(500,200),FONT_HERSHEY_SCRIPT_COMPLEX,3.0,Scalar(14,173,,238),2,8);
    

    其效果如下所示:


    opencv对于中文字符的输出,需要引入以下两个文件

    • putText.h
    #pragma once
    #ifndef PUTTEXT_H_
    #define PUTTEXT_H_
    
    #include <windows.h>
    #include <string>
    #include <opencv2/opencv.hpp>
    
    using namespace cv;
    
    void GetStringSize(HDC hDC, const char* str, int* w, int* h);
    void putTextZH(Mat& dst, const char* str, Point org, Scalar color, int fontSize,
        const char* fn = "Arial", bool italic = false, bool underline = false);
    
    #endif // PUTTEXT_H_
    
    
    
    • putText.cpp
    #include "putText.h"
    
    void GetStringSize(HDC hDC, const char* str, int* w, int* h)
    {
        SIZE size;
        GetTextExtentPoint32A(hDC, str, strlen(str), &size);
        if (w != 0) *w = size.cx;
        if (h != 0) *h = size.cy;
    }
    
    void putTextZH(Mat& dst, const char* str, Point org, Scalar color, int fontSize, const char* fn, bool italic, bool underline)
    {
        CV_Assert(dst.data != 0 && (dst.channels() == 1 || dst.channels() == 3));
    
        int x, y, r, b;
        if (org.x > dst.cols || org.y > dst.rows) return;
        x = org.x < 0 ? -org.x : 0;
        y = org.y < 0 ? -org.y : 0;
    
        LOGFONTA lf;
        lf.lfHeight = -fontSize;
        lf.lfWidth = 0;
        lf.lfEscapement = 0;
        lf.lfOrientation = 0;
        lf.lfWeight = 5;
        lf.lfItalic = italic;   //斜体
        lf.lfUnderline = underline; //下划线
        lf.lfStrikeOut = 0;
        lf.lfCharSet = DEFAULT_CHARSET;
        lf.lfOutPrecision = 0;
        lf.lfClipPrecision = 0;
        lf.lfQuality = PROOF_QUALITY;
        lf.lfPitchAndFamily = 0;
        strcpy_s(lf.lfFaceName, fn);
    
        HFONT hf = CreateFontIndirectA(&lf);
        HDC hDC = CreateCompatibleDC(0);
        HFONT hOldFont = (HFONT)SelectObject(hDC, hf);
    
        int strBaseW = 0, strBaseH = 0;
        int singleRow = 0;
        char buf[1 << 12];
        strcpy_s(buf, str);
        char* bufT[1 << 12];  // 这个用于分隔字符串后剩余的字符,可能会超出。
        //处理多行
        {
            int nnh = 0;
            int cw, ch;
    
            const char* ln = strtok_s(buf, "\n", bufT);
            while (ln != 0)
            {
                GetStringSize(hDC, ln, &cw, &ch);
                strBaseW = max(strBaseW, cw);
                strBaseH = max(strBaseH, ch);
    
                ln = strtok_s(0, "\n", bufT);
                nnh++;
            }
            singleRow = strBaseH;
            strBaseH *= nnh;
        }
    
        if (org.x + strBaseW < 0 || org.y + strBaseH < 0)
        {
            SelectObject(hDC, hOldFont);
            DeleteObject(hf);
            DeleteObject(hDC);
            return;
        }
    
        r = org.x + strBaseW > dst.cols ? dst.cols - org.x - 1 : strBaseW - 1;
        b = org.y + strBaseH > dst.rows ? dst.rows - org.y - 1 : strBaseH - 1;
        org.x = org.x < 0 ? 0 : org.x;
        org.y = org.y < 0 ? 0 : org.y;
    
        BITMAPINFO bmp = { 0 };
        BITMAPINFOHEADER& bih = bmp.bmiHeader;
        int strDrawLineStep = strBaseW * 3 % 4 == 0 ? strBaseW * 3 : (strBaseW * 3 + 4 - ((strBaseW * 3) % 4));
    
        bih.biSize = sizeof(BITMAPINFOHEADER);
        bih.biWidth = strBaseW;
        bih.biHeight = strBaseH;
        bih.biPlanes = 1;
        bih.biBitCount = 24;
        bih.biCompression = BI_RGB;
        bih.biSizeImage = strBaseH * strDrawLineStep;
        bih.biClrUsed = 0;
        bih.biClrImportant = 0;
    
        void* pDibData = 0;
        HBITMAP hBmp = CreateDIBSection(hDC, &bmp, DIB_RGB_COLORS, &pDibData, 0, 0);
    
        CV_Assert(pDibData != 0);
        HBITMAP hOldBmp = (HBITMAP)SelectObject(hDC, hBmp);
    
        //color.val[2], color.val[1], color.val[0]
        SetTextColor(hDC, RGB(255, 255, 255));
        SetBkColor(hDC, 0);
        //SetStretchBltMode(hDC, COLORONCOLOR);
    
        strcpy_s(buf, str);
        const char* ln = strtok_s(buf, "\n", bufT);
        int outTextY = 0;
        while (ln != 0)
        {
            TextOutA(hDC, 0, outTextY, ln, strlen(ln));
            outTextY += singleRow;
            ln = strtok_s(0, "\n", bufT);
        }
        uchar* dstData = (uchar*)dst.data;
        int dstStep = dst.step / sizeof(dstData[0]);
        unsigned char* pImg = (unsigned char*)dst.data + org.x * dst.channels() + org.y * dstStep;
        unsigned char* pStr = (unsigned char*)pDibData + x * 3;
        for (int tty = y; tty <= b; ++tty)
        {
            unsigned char* subImg = pImg + (tty - y) * dstStep;
            unsigned char* subStr = pStr + (strBaseH - tty - 1) * strDrawLineStep;
            for (int ttx = x; ttx <= r; ++ttx)
            {
                for (int n = 0; n < dst.channels(); ++n) {
                    double vtxt = subStr[n] / 255.0;
                    int cvv = vtxt * color.val[n] + (1 - vtxt) * subImg[n];
                    subImg[n] = cvv > 255 ? 255 : (cvv < 0 ? 0 : cvv);
                }
    
                subStr += 3;
                subImg += dst.channels();
            }
        }
    
        SelectObject(hDC, hOldBmp);
        SelectObject(hDC, hOldFont);
        DeleteObject(hf);
        DeleteObject(hBmp);
        DeleteDC(hDC);
    }
    

    引入以上两个文件后,可以很方便的实现,在图像上输出中文字符的功能,代码如下:

    #include<iostream>
    #include<opencv2/opencv.hpp>
    #include"putText.h"
    using namespace cv;
    
    /*
    load and display grayscale image
    draw color text onto image
    */
    
    int main()
    {
        Mat m = imread("timg.jpg");
        Mat m2gray, gray2m;
        cvtColor(m, m2gray, COLOR_BGR2GRAY);
        cvtColor(m2gray, gray2m, COLOR_GRAY2BGR);
        putTextZH(m, "长\n云\n", Point(1150, 120), Scalar(230, 230, 230), 55, "迷你简启体");
        
        putTextZH(m, "暗\n雪\n山\n", Point(1220, 185), Scalar(230, 230, 230), 55, "迷你简启体");
                
        imshow("image_text", m);
        imwrite("image_textZH.jpg", m);
        waitKey(0);
        return 0;
    }
    
    

    其效果如下:


    相关文章

      网友评论

          本文标题:opencv在图片中输入字符

          本文链接:https://www.haomeiwen.com/subject/ttmrnktx.html