Opencv框选黑色字体进行替换(涉及知识点:selectROI,在控制台输入字体大小,颜色,内容替换所选择的区域)

import cv2
from PIL import Image,ImageDraw,ImageFont
import numpy as np

img_path = '../img/'
img_clean_path = '../img_clean/'
name = 'xiao_ben'
suf = '.png'

img = cv2.imread(img_path+name+suf)
cv2.imshow('original', img)

# 选择ROI
roi = cv2.selectROI(windowName="original", img=img, showCrosshair=False, fromCenter=False)
x, y, w, h = roi
print(roi)

# roi_new = cv2.medianBlur(img[y:y + h, x:x + w],3)
img[y:y + h, x:x + w] = [255,255,255]
img_new = img.copy()
cv2.imwrite(f'{img_clean_path+name}_clean'+suf,img_new)

font_size = int(input('请输入字体大小:'))
cv2.imshow('img_new', img_new)


pil_img = Image.open(f'{img_clean_path+name}_clean'+suf)
draw = ImageDraw.Draw(pil_img)

# 第一个参数是字体文件的路径,第二个是字体大小
font = ImageFont.truetype('simhei.ttf',font_size,encoding='utf-8')

img_new = cv2.imread(f'{img_clean_path+name}_clean'+suf)
roi = cv2.selectROI(windowName="img_new", img=img_new, showCrosshair=False, fromCenter=False)
x, y, w, h = roi
print(roi)

txt = input('请输入文本:')
color_value = ''
color = input('请输入颜色(白、黑):')
if color == '白':
    color_value = (255,255,255)
else:
    color_value = (0,0,0)
draw.text((x,y),txt,color_value,font=font)

# PIL图片转cv2
cv2_text_im = cv2.cvtColor(np.array(pil_img),cv2.COLOR_RGB2BGR)

# 变得可以拉伸 winname 必须要一样,且设置可以拉伸在前面
cv2.namedWindow('tupian', cv2.WINDOW_NORMAL)

# 显示
cv2.imshow('tupian',cv2_text_im)
cv2.imwrite(f'{img_clean_path+name}_clean'+suf,cv2_text_im)


# 退出
cv2.waitKey(0)
cv2.destroyAllWindows()

选择黑色字体,按enter:
Opencv框选黑色字体进行替换(涉及知识点:selectROI,在控制台输入字体大小,颜色,内容替换所选择的区域)_第1张图片
黑色字体被去除了:
Opencv框选黑色字体进行替换(涉及知识点:selectROI,在控制台输入字体大小,颜色,内容替换所选择的区域)_第2张图片
在这里插入图片描述
在控制台输入字体大小和颜色,将输入的文本显示在图片上:

Opencv框选黑色字体进行替换(涉及知识点:selectROI,在控制台输入字体大小,颜色,内容替换所选择的区域)_第3张图片

你可能感兴趣的:(opencv笔记,opencv,人工智能,计算机视觉)