亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

1.方法一:轉PIL后使用PIL相關函數(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圖片轉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ù)
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()

缺點:編譯過程復雜繁瑣,容易報一些列的錯誤,編譯時確保已安裝第三方庫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版本

編譯過程較復雜,不推薦。

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)點:耗時幾乎沒有

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

相關文章

  • python實例小練習之Turtle繪制南方的雪花

    python實例小練習之Turtle繪制南方的雪花

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

    分享幾種python 變量合并方法

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

    Python中Playwright模塊進行自動化測試的實現(xiàn)

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

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

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

    python用戶自定義異常的實例講解

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

    一文教你利用Python畫花樣圖

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

    如何用scheduler實現(xiàn)learning-rate學習率動態(tài)變化

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

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

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

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

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

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

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

最新評論