1.確定特定字體類型;
2.收集合適的圖片作為背景
3.在背景圖上填寫特定字體的字符內容
1)字體無法確認時怎么辦?
方法一:可以將文本行裁剪出來去網站上確認,網站鏈接:字體識別-在線掃一掃圖片找字體-搜字體!
方法二:將文字輸入到文檔文件中,更換不同的字體,看是否與字體目標匹配;
字體可以去網上下載,也可以在本機查找;本機的字體所在位置:
個人用戶字體文件:~/.local/share/fonts
系統字體文件:/usr/share/fonts
字體配置文件:/etc/fonts/
下面是我處理的代碼,僅供參考:
def check_dir1(path):if not os.path.exists(path):os.mkdir(path)else:files = os.listdir(path)for file in files:file_path = os.path.join(path, file)os.remove(file_path)
'''
制作一些文本行數據
'''
from PIL import ImageFont, ImageDraw
import PIL.Image as PImage
import random
import os
import numpy as np
import cv2
from rec.temporary_boundary.line_process import cut_line3_1
from result_process.preprocess import check_dir1if __name__=='__main__':cha_list = ['A','B','C','D','E','F','G','H','I','J','K',\'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']save_dir = '/home/fuxueping/4tdisk/data/certificate_reader/北京現場測試數據/20240614針對識別問題/SAU_name'check_dir1(save_dir)txt_parh = '/home/fuxueping/4tdisk/data/certificate_reader/北京現場測試數據/20240614針對識別問題/SAU_name.txt'bg_img_dir = '/home/fuxueping/4tdisk/data/certificate_reader/北京現場測試數據/20240614針對識別問題/bg'bg_imgs = os.listdir(bg_img_dir)f_save = open(txt_parh, 'w', encoding='utf-8')check_dir1(save_dir)num = 50while num:all_num = 0bg_img = random.choice(bg_imgs)num1=random.choice([2, 3])chr_str = ''all_num += num1while num1:chr_ = random.choice(cha_list)chr_str += chr_num1 -=1char_med = ''for i in range(3):num2=random.choice([5,6,7,8])chr_str2=''all_num += num2while num2:chr_ = random.choice(cha_list)chr_str2 += chr_num2 -= 1if i == 0:char_med += chr_str2+', 'elif i == 1:char_med += chr_str2 + ' 'elif i == 2:char_med += chr_str2 + ' 'chr_1 = random.choice(cha_list)result_str = chr_str+' '+char_med+chr_1all_num += 1im = PImage.open(os.path.join(bg_img_dir, bg_img))w, h = im.sizefont_size = 24w_len = int(0 + all_num * (font_size-3) + 4)if w_len > w:num -= 1continuename_font = ImageFont.truetype('/home/fuxueping/4tdisk/data/certificate_reader/北京現場測試數據/20240614針對識別問題/fonts/n019003l.pfb', font_size)draw = ImageDraw.Draw(im)y_len = random.randint(0, h-font_size-5)color = tuple([random.randint(0, 20) for _ in range(3)])draw.text((2, y_len), result_str, fill=color, font=name_font)box = (0, y_len, w_len, y_len+font_size+5)rect_img = im.crop(box)image_array = np.array(rect_img)cv2_image = cv2.cvtColor(image_array, cv2.COLOR_RGB2BGR)result, _ = cut_line3_1(cv2_image)if len(result):region_rec = cv2_image[result[1]:result[3], result[0]:min(w, result[2]+2)] # 裁剪出待識別的區域image_array = cv2.cvtColor(region_rec, cv2.COLOR_BGR2RGB)rect_img = PImage.fromarray(image_array)# image_array = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2RGB)# rect_img = PImage.fromarray(image_array)save_path = os.path.join(save_dir, str(num)+'_'+result_str+'.jpg')line = save_path+'\t'+result_str+'\n'f_save.write(line)rect_img.save(save_path)num -= 1f_save.close()
# 根據設定的閾值和圖片直方圖,找出波峰,用于分隔字符
def find_waves_row(threshold, histogram):#行數是59# up_point = -1 # 上升點# is_peak = False# if histogram[0] >= threshold:up_point = 0 #起始位置is_peak = Truewave_peaks = []top_cut = []for i, x in enumerate(histogram): #x是對應的像素和,i是行if is_peak and x >= threshold:if i - up_point >=2 :# top_cut.append((up_point, i)) #加這一行,相當于裁減掉多于的空行up_point = i-1else:up_point = iis_peak = Falseelif not is_peak and x < threshold:#隨后找到字符消失的位置is_peak = Trueif 1 < i < histogram.shape[0]-1:#行數不是在開頭也不在結尾wave_peaks.append((up_point, i+1))else:wave_peaks.append((up_point, i))up_point = i# if is_peak and up_point != -1 and i - up_point > 4:# wave_peaks.append((up_point, i))if not is_peak and x >= threshold:#雖然數據已經結束,但是沒有出現小于閾值的情況wave_peaks.append((up_point, i))return wave_peaksdef cut_line3_1(rgb_img, kernel_size = 3, y_len = 5, row_threshold=255 * 1, col_thresh = 255*1):'''切割出每一行,只保留高度滿足條件的一行內容,然后切除掉每一行的前端后尾端的空白'''rgb_img = method_9(rgb_img) #高斯濾波# 使用sauvola進行二值化h, w = rgb_img.shape[:2]sau_bin = sauvola_bin(rgb_img) #sauvola二值化# cv2.imwrite('./../temp/sauvola_bin.jpg', sau_bin)# sau_bin = get_charcter_region(rgb_img) # 局部區域算閾值二值化# cv2.imwrite('./../temp/sau_bin1.jpg', sau_bin)sau_bin_inv = 255 - sau_bin# cv2.imwrite('./../temp/sau_bin_inv1.jpg', sau_bin_inv)if kernel_size != 0:sau_bin_inv = cv2.medianBlur(sau_bin_inv, kernel_size)# cv2.imwrite('./../temp/sau_bin_inv_dinose1.jpg', sau_bin_inv)col_histogram = np.sum(sau_bin_inv, axis=1)wave_peaks = find_waves_row(col_thresh, col_histogram)result = []#找出高度最大的區域,只保留一行內容max_y = 0result_y = []if not len(wave_peaks):return [], sau_bin_invfor i, wave_peak in enumerate(wave_peaks):y1 = wave_peak[0]y2 = wave_peak[1]if y2 - y1 < y_len: #20之前是這個閾值 ,將高度不滿足>=5的字符區域去掉continueif max_y < y2 - y1:max_y = y2 - y1result_y = [y1, y2]if len(result_y): #有時候裁剪的圖片可能是沒有字符,這種情況多出現在證件類別錯誤的情況y1 = result_y[0]y2 = result_y[1]else:return [], sau_bin_invline_img = sau_bin_inv[y1:y2, :]# line_img_bgr = rgb_img[wave_peak[0]:wave_peak[1], :]# save_other = os.path.join(save_path, file + '_'+str(i)+'.jpg')# cv2.imwrite(save_other, line_img)row_histogram = np.sum(line_img, axis=0) # 數組的每一列求和# row_max = np.max(row_histogram)# row_threshold = row_max - 255*1wave_peaks_line = find_waves_col(row_threshold, row_histogram)# cv2.imwrite('./../temp/line_img.jpg', line_img)x1 = 0x2 = wresult_ = []for wave_ in wave_peaks_line:len_x = wave_[1] - wave_[0]if len_x > 5:result_.append(wave_)if len(result_): # 有時候朝水平投影內容消失了,就用【0,w】代替x1 = result_[0][0]x2 = result_[-1][1]return [x1, y1, x2, y2], sau_bin_inv