小言_互联网的博客

在OpenCV里绘制直线、圆、中文等图形

590人阅读  评论(0)

前面学习过寻找图像的边缘,需要在图像标记出来,这时就需要在图像上画一些图形,那么这里就来学习cv.line(), cv.circle() , cv.rectangle(), cv.ellipse()来怎么样绘制图形的,以及使用cv.putText()输出文本。下面来看一下cv.line()函数的定义:

img 绘制的图像

pt1 直线的起点

pt2 直线的终点

color 直线颜色

thickness 直线的粗细

lineType 直线的绘制方式

shift 坐标点的小数点位数

 

其它函数的参数大同小异,通过下面的例子来演示:

#python 3.7.4,opencv4.1
#蔡军生 https://blog.csdn.net/caimouse/article/details/51749579
#
import numpy as np
import cv2
from matplotlib import pyplot as plt
import freetype

#使用freetype显示中文类
class put_chinese_text(object):
    def __init__(self, ttf):
        self._face = freetype.Face(ttf) 

    def draw_text(self, image, pos, text, text_size, text_color):

        '''
        draw chinese(or not) text with ttf
        :param image:     image(numpy.ndarray) to draw text
        :param pos:       where to draw text
        :param text:      the context, for chinese should be unicode type
        :param text_size: text size
        :param text_color:text color
        :return:          image       '''

        self._face.set_char_size(text_size * 64)
        metrics = self._face.size
        ascender = metrics.ascender/64.0
        ypos = int(ascender) 

        image = self.draw_string(image, pos[0], pos[1]+ypos, text, text_color)

        return image 

    def draw_string(self, image, x_pos, y_pos, text, color):

        ''' draw string
        :param x_pos: text x-postion on image
        :param y_pos: text y-postion on image
        :param text:  text (unicode)
        :param color: text color
        :return:      image
        '''
        prev_char = 0
        pen = freetype.Vector()
        pen.x = x_pos << 6   # div 64
        pen.y = y_pos << 6 

        hscale = 1.0
        matrix = freetype.Matrix(int(hscale)*0x10000, int(0.2*0x10000),\
                                 int(0.0*0x10000), int(1.1*0x10000))

        cur_pen = freetype.Vector()
        pen_translate = freetype.Vector() 

        for cur_char in text:
            self._face.set_transform(matrix, pen_translate) 

            self._face.load_char(cur_char)
            kerning = self._face.get_kerning(prev_char, cur_char)
            pen.x += kerning.x
            slot = self._face.glyph
            bitmap = slot.bitmap 

            cur_pen.x = pen.x
            cur_pen.y = pen.y - slot.bitmap_top * 64
            self.draw_ft_bitmap(image, bitmap, cur_pen, color) 

            pen.x += slot.advance.x
            prev_char = cur_char

        return image 

    def draw_ft_bitmap(self, img, bitmap, pen, color):
        '''
        draw each char
        :param bitmap: bitmap
        :param pen:    pen
        :param color:  pen color e.g.(0,0,255) - red
        :return:       image
        '''
        x_pos = pen.x >> 6
        y_pos = pen.y >> 6
        cols = bitmap.width
        rows = bitmap.rows
        glyph_pixels = bitmap.buffer 

        for row in range(rows):
            for col in range(cols):
                if glyph_pixels[row*cols + col] != 0:
                    img[y_pos + row,x_pos + col] = color

                    
# 创建一个黑色彩色图像
img = np.zeros((512,512,3), np.uint8)

# 画一条5像素宽的蓝色直线,注意颜色顺序是(B,G,R)
cv2.line(img,(0,0),(511,511),(255,0,0),5)
#画圆
cv2.circle(img,(447,63), 63, (0,0,255), -1)
#画椭圆
cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
#画多边形
pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(img,[pts],True,(0,255,255))
#输出文字
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)

#显示中文
color_ = (0,255,0) # (B,G,R) 中文显示颜色
pos = (30, 100) #显示位置
text_size = 24 #文字大小
lineTxt = '深圳先行示范区' #要显示文字

ft = put_chinese_text("C:/windows/fonts/simfang.ttf") #使用windows下的字体
image = ft.draw_text(img, pos, lineTxt, text_size, color_)

cv2.imshow('Out', image)

cv2.waitKey(0)
cv2.destroyAllWindows()

结果输出如下

 

在这个例子里,显示英文字符都是很简单的事情,因为OpenCV直接支持输出,如果要显示中文就不简单了,需要先安装freetype-py,并且要按freetype的方式生成bmp,再按字体的格式来显示像素。如果没有安装它,可以按下面命令进行安装:

pip install freetype-py

 

然后定义一个类来显示中文:

#使用freetype显示中文类

class put_chinese_text(object):

 

这里是构造函数,调用freetype.Face读取字体。

    def __init__(self, ttf):

        self._face = freetype.Face(ttf)

 

显示一行文字的函数

    def draw_text(self, image, pos, text, text_size, text_color):

 

        '''

        draw chinese(or not) text with ttf

        :param image:     image(numpy.ndarray) to draw text

        :param pos:       where to draw text

        :param text:      the context, for chinese should be unicode type

        :param text_size: text size

        :param text_color:text color

        :return:          image       '''

 

        self._face.set_char_size(text_size * 64)

        metrics = self._face.size

        ascender = metrics.ascender/64.0

        ypos = int(ascender)

 

        image = self.draw_string(image, pos[0], pos[1]+ypos, text, text_color)

 

        return image

 

 

根据计算出来的坐标位置显示字符串

    def draw_string(self, image, x_pos, y_pos, text, color):

 

        ''' draw string

        :param x_pos: text x-postion on image

        :param y_pos: text y-postion on image

        :param text:  text (unicode)

        :param color: text color

        :return:      image

        '''

        prev_char = 0

        pen = freetype.Vector()

        pen.x = x_pos << 6   # div 64

        pen.y = y_pos << 6

 

        hscale = 1.0

        matrix = freetype.Matrix(int(hscale)*0x10000, int(0.2*0x10000),\

                                 int(0.0*0x10000), int(1.1*0x10000))

 

        cur_pen = freetype.Vector()

        pen_translate = freetype.Vector()

 

        for cur_char in text:

            self._face.set_transform(matrix, pen_translate)

 

            self._face.load_char(cur_char)

            kerning = self._face.get_kerning(prev_char, cur_char)

            pen.x += kerning.x

            slot = self._face.glyph

            bitmap = slot.bitmap

 

            cur_pen.x = pen.x

            cur_pen.y = pen.y - slot.bitmap_top * 64

            self.draw_ft_bitmap(image, bitmap, cur_pen, color)

 

            pen.x += slot.advance.x

            prev_char = cur_char

 

        return image

 

显示每个汉字的位图数据。

    def draw_ft_bitmap(self, img, bitmap, pen, color):

        '''

        draw each char

        :param bitmap: bitmap

        :param pen:    pen

        :param color:  pen color e.g.(0,0,255) - red

        :return:       image

        '''

        x_pos = pen.x >> 6

        y_pos = pen.y >> 6

        cols = bitmap.width

        rows = bitmap.rows

        glyph_pixels = bitmap.buffer

 

        for row in range(rows):

            for col in range(cols):

                if glyph_pixels[row*cols + col] != 0:

                    img[y_pos + row,x_pos + col] = color

https://blog.csdn.net/caimouse/article/details/51749579


转载:https://blog.csdn.net/caimouse/article/details/102525550
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场