欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python 解決OpenCV顯示中文字符的方法匯總

 更新時(shí)間:2024年04月03日 11:19:17   作者:何時(shí)擺脫命運(yùn)的束縛  
因工作需要,要在圖片中顯示中文字符,并且要求速度足夠快,在網(wǎng)上搜羅一番后,總結(jié)下幾個(gè)解決方法,對(duì)python 解決OpenCV顯示中文字符相關(guān)知識(shí)感興趣的朋友一起看看吧

因工作需要,要在圖片中顯示中文字符,并且要求速度足夠快,在網(wǎng)上搜羅一番后,總結(jié)下幾個(gè)解決方法。

1.方法一:轉(zhuǎn)PIL后使用PIL相關(guān)函數(shù)添加中文字符

from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np
# cv2讀取圖片,名稱不能有漢字
img = cv2.imread('pic1.jpeg') 
# cv2和PIL中顏色的hex碼的儲(chǔ)存順序不同
cv2img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 
pilimg = Image.fromarray(cv2img)
# PIL圖片上打印漢字
draw = ImageDraw.Draw(pilimg) # 圖片上打印
#simsun 宋體
font = ImageFont.truetype("simsun.ttf", 40, encoding="utf-8") 
#位置,文字,顏色==紅色,字體引入
draw.text((20, 20), "你好", (255, 0, 0), font=font) 
# PIL圖片轉(zhuǎn)cv2 圖片
cv2charimg = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)
cv2.imshow("img", cv2charimg)
cv2.waitKey (0)
cv2.destroyAllWindows()

存在的缺點(diǎn):cv2->pil 中 Image.fromarray(img)存在耗時(shí)4~5ms

2.方法二:opencv重新編譯帶freetype

編譯過(guò)程略。

import cv2
import numpy as np
# 創(chuàng)建一個(gè)黑色的圖像
img = np.zeros((300, 500, 3), dtype=np.uint8)
# 中文文本
text = '你好,OpenCV!'
# 設(shè)置字體相關(guān)參數(shù)
font_path = 'path/to/your/chinese/font.ttf'  # 替換為你的中文字體文件路徑
font_size = 24
font_color = (255, 255, 255)
thickness = 2
# 使用 truetype 字體加載中文字體
font = cv2.freetype.createFreeType2()
font.loadFontData(font_path)
# 在圖像上放置中文文本
position = (50, 150)
font.putText(img, text, position, font_size, font_color, thickness=thickness)
# 顯示圖像
cv2.imshow('Image with Chinese Text', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

缺點(diǎn):編譯過(guò)程復(fù)雜繁瑣,容易報(bào)一些列的錯(cuò)誤,編譯時(shí)確保已安裝第三方庫(kù)freetype和harfbuzz,并且配置編譯參數(shù)時(shí)需打開(kāi)freetype。

3.方法三:使用freetype-py

pip install freetype-py

ft.py

import numpy as np
import freetype
import copy
import pdb
import time
class PutChineseText(object):
    def __init__(self, ttf, text_size):
        self._face = freetype.Face(ttf)
        hscale = 1.0
        self.matrix = freetype.Matrix(int(hscale)*0x10000, int(0.2*0x10000),int(0.0*0x10000), int(1.1*0x10000))
        self.cur_pen = freetype.Vector()
        self.pen_translate = freetype.Vector()
        self._face.set_transform(self.matrix, self.pen_translate)
        self._face.set_char_size(text_size * 64)
        metrics = self._face.size
        ascender = metrics.ascender/64.0
        #descender = metrics.descender/64.0
        #height = metrics.height/64.0
        #linegap = height - ascender + descender
        self.ypos = int(ascender)
        self.pen = freetype.Vector()
    def draw_text(self, image, pos, text, 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
        '''
        # if not isinstance(text, unicode):
        #     text = text.decode('utf-8')
        img = self.draw_string(image, pos[0], pos[1]+self.ypos, text, text_color)
        return img
    def draw_string(self, img, x_pos, y_pos, text, color):
        '''
        draw string
        :param x_pos: text x-postion on img
        :param y_pos: text y-postion on img
        :param text:  text (unicode)
        :param color: text color
        :return:      image
        '''
        prev_char = 0
        self.pen.x = x_pos << 6   # div 64
        self.pen.y = y_pos << 6
        image = copy.deepcopy(img)
        for cur_char in text:
            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
            self.pen.x += 0
            self.cur_pen.x = self.pen.x
            self.cur_pen.y = self.pen.y - slot.bitmap_top * 64
            self.draw_ft_bitmap(image, bitmap, self.cur_pen, color)
            self.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][0] = color[0]
                    img[y_pos + row][x_pos + col][1] = color[1]
                    img[y_pos + row][x_pos + col][2] = color[2]
if __name__ == '__main__':
    # just for test
    import cv2
    line = '你好'
    img = np.zeros([300,300,3])
    color_ = (0,255,0) # Green
    pos = (40, 40)
    text_size = 24
    ft = PutChineseText('font/simsun.ttc',text_size=20)
    t1 = time.time()
    image = ft.draw_text(img, pos, line, color_)
    print(f'draw load . ({time.time() - t1:.3f}s)')
    cv2.imshow('ss', image)
    cv2.waitKey(0)

缺點(diǎn):每個(gè)字符耗時(shí)在0.3~1ms左右,耗時(shí)略大。

4.方法四:使用OpenCV5.0

4.1 編譯opencv5.x版本

編譯過(guò)程較復(fù)雜,不推薦。

4.2 使用rolling版本

卸載原先安裝的opencv

pip uninstall opencv-python
pip uninstall opencv-contrib-python

安裝rolling版本

pip install opencv-python-rolling
pip install opencv-contrib-python-rolling

安裝完畢后,cv2.putText即可支持中文字符。

缺點(diǎn):5.0版本暫未正式發(fā)布,可能存在不穩(wěn)定情況

優(yōu)點(diǎn):耗時(shí)幾乎沒(méi)有

到此這篇關(guān)于python 解決OpenCV顯示中文字符的文章就介紹到這了,更多相關(guān)python 顯示中文字符內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python實(shí)例小練習(xí)之Turtle繪制南方的雪花

    python實(shí)例小練習(xí)之Turtle繪制南方的雪花

    Turtle庫(kù)是Python語(yǔ)言中一個(gè)很流行的繪制圖像的函數(shù)庫(kù),想象一個(gè)小烏龜,在一個(gè)橫軸為x、縱軸為y的坐標(biāo)系原點(diǎn),(0,0)位置開(kāi)始,它根據(jù)一組函數(shù)指令的控制,在這個(gè)平面坐標(biāo)系中移動(dòng),從而在它爬行的路徑上繪制了圖形
    2021-09-09
  • 分享幾種python 變量合并方法

    分享幾種python 變量合并方法

    這篇文章主要介紹了分享python 變量的合并幾種方法,分享內(nèi)容有l(wèi)ist 合并和str 合并以及dict 合并的分析,下面具體方法介紹,需要的小伙伴可以參考一下
    2022-03-03
  • Python中Playwright模塊進(jìn)行自動(dòng)化測(cè)試的實(shí)現(xiàn)

    Python中Playwright模塊進(jìn)行自動(dòng)化測(cè)試的實(shí)現(xiàn)

    playwright是由微軟開(kāi)發(fā)的Web UI自動(dòng)化測(cè)試工具,本文主要介紹了Python中Playwright模塊進(jìn)行自動(dòng)化測(cè)試的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-12-12
  • 淺談python中np.array的shape( ,)與( ,1)的區(qū)別

    淺談python中np.array的shape( ,)與( ,1)的區(qū)別

    今天小編就為大家分享一篇python中np.array的shape ( ,)與( ,1)的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • python用戶自定義異常的實(shí)例講解

    python用戶自定義異常的實(shí)例講解

    在本篇文章里小編給大家整理的是一篇關(guān)于python用戶自定義異常的實(shí)例講解,以后需要的朋友們可以跟著學(xué)習(xí)參考下。
    2021-07-07
  • 一文教你利用Python畫花樣圖

    一文教你利用Python畫花樣圖

    這篇文章主要給大家介紹了關(guān)于如何利用Python畫花樣圖的相關(guān)資料,文中通過(guò)示例代碼以及圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2021-10-10
  • 如何用scheduler實(shí)現(xiàn)learning-rate學(xué)習(xí)率動(dòng)態(tài)變化

    如何用scheduler實(shí)現(xiàn)learning-rate學(xué)習(xí)率動(dòng)態(tài)變化

    這篇文章主要介紹了如何用scheduler實(shí)現(xiàn)learning-rate學(xué)習(xí)率動(dòng)態(tài)變化問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python?OLS?雙向逐步回歸方式

    Python?OLS?雙向逐步回歸方式

    這篇文章主要介紹了Python?OLS?雙向逐步回歸方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • 如何利用Python實(shí)現(xiàn)自動(dòng)打卡簽到的實(shí)踐

    如何利用Python實(shí)現(xiàn)自動(dòng)打卡簽到的實(shí)踐

    簽到,都是規(guī)律性的操作,何嘗不寫一個(gè)程序加到Windows實(shí)現(xiàn)自動(dòng)簽到呢,本文就主要介紹了如何利用Python實(shí)現(xiàn)自動(dòng)打卡簽到的實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下
    2021-12-12
  • 使用Python遍歷文件夾實(shí)現(xiàn)查找指定文件夾

    使用Python遍歷文件夾實(shí)現(xiàn)查找指定文件夾

    這篇文章主要為大家介紹了如何使用Python遍歷文件夾從而實(shí)現(xiàn)查找指定文件夾下所有相同名稱的文件、所有相同后綴名的文件,感興趣的可以了解一下
    2022-07-07

最新評(píng)論