最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

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碼的儲存順序不同
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()

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

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

編譯過程略。

import cv2
import numpy as np
# 創(chuàng)建一個黑色的圖像
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()

缺點:編譯過程復(fù)雜繁瑣,容易報一些列的錯誤,編譯時確保已安裝第三方庫freetype和harfbuzz,并且配置編譯參數(shù)時需打開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)

缺點:每個字符耗時在0.3~1ms左右,耗時略大。

4.方法四:使用OpenCV5.0

4.1 編譯opencv5.x版本

編譯過程較復(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即可支持中文字符。

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

優(yōu)點:耗時幾乎沒有

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

相關(guān)文章

  • 對python的bytes類型數(shù)據(jù)split分割切片方法

    對python的bytes類型數(shù)據(jù)split分割切片方法

    今天小編就為大家分享一篇對python的bytes類型數(shù)據(jù)split分割切片方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • 零基礎(chǔ)教你使用Python一鍵生成Excel圖表

    零基礎(chǔ)教你使用Python一鍵生成Excel圖表

    在日常辦公和數(shù)據(jù)分析中,Excel圖表是我們展示數(shù)據(jù)最直觀的工具,本文專為零基礎(chǔ)編程新手設(shè)計,將系統(tǒng)地帶你了解如何使用Python在Excel中制作柱狀圖,告別繁瑣的手工操作
    2026-04-04
  • 在腳本中單獨使用django的ORM模型詳解

    在腳本中單獨使用django的ORM模型詳解

    這篇文章主要介紹了在腳本中單獨使用django的ORM模型詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • 詳解Python中的裝飾器、閉包和functools的教程

    詳解Python中的裝飾器、閉包和functools的教程

    這篇文章主要介紹了詳解Python中的裝飾器、閉包和functools的教程,作者還給出了相關(guān)的Flask框架下的應(yīng)用實例,需要的朋友可以參考下
    2015-04-04
  • 解決pycharm最左側(cè)Tool Buttons顯示不全的問題

    解決pycharm最左側(cè)Tool Buttons顯示不全的問題

    今天小編就為大家分享一篇解決pycharm最左側(cè)Tool Buttons顯示不全的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • linux下安裝easy_install的方法

    linux下安裝easy_install的方法

    python中的easy_install工具,類似于Php中的pear,或者Ruby中的gem,或者Perl中的cpan,那是相當(dāng)?shù)乃嵬崃巳绻胧褂?/div> 2013-02-02
  • linux環(huán)境下Django的安裝配置詳解

    linux環(huán)境下Django的安裝配置詳解

    這篇文章主要介紹了linux環(huán)境下Django的安裝配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-07-07
  • Python NumPy實現(xiàn)數(shù)組排序與過濾示例分析講解

    Python NumPy實現(xiàn)數(shù)組排序與過濾示例分析講解

    NumPy是Python的一種開源的數(shù)值計算擴展,它支持大量的維度數(shù)組與矩陣運算,這篇文章主要介紹了使用NumPy實現(xiàn)數(shù)組排序與過濾的方法,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-05-05
  • NLTK 3.2.4 環(huán)境搭建教程

    NLTK 3.2.4 環(huán)境搭建教程

    這篇文章主要為大家詳細(xì)介紹了NLTK 3.2.4 環(huán)境搭建教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • PyQt5頁面跳轉(zhuǎn)問題及解決方式

    PyQt5頁面跳轉(zhuǎn)問題及解決方式

    本文主要介紹了PyQt5頁面跳轉(zhuǎn)問題及解決方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01

最新評論

东乌| 安康市| 谢通门县| 陵水| 龙岩市| 泰安市| 宁晋县| 乌拉特中旗| 曲阜市| 阿鲁科尔沁旗| 曲沃县| 肇东市| 津市市| 石家庄市| 宝鸡市| 南城县| 通辽市| 河西区| 丹寨县| 宜黄县| 乌兰察布市| 安丘市| 金堂县| 垣曲县| 中江县| 天气| 台东市| 扎赉特旗| 定西市| 育儿| 十堰市| 黄陵县| 扶风县| 瑞金市| 施秉县| 水富县| 即墨市| 文成县| 通州区| 昌吉市| 南木林县|