如何使用python从彩色图像中删除文本

2024-04-19 03:16:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试从下面的照片1中删除背景和白色文本,但我只能删除这些图像2{a3}。圆圈内仍有白色文字。 我使用了以下代码。 我非常感谢大家的帮助

img = cv2.imread('sample.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#Crop image
croped_img = img[51:403,102:454]
#plt.imshow(croped_img)
radius = 176
cx, cy = radius, radius # The center of circle
x,y = np.ogrid[-radius: radius, -radius: radius]
index = x**2 + y**2 > radius**2
croped_img[cy-radius:cy+radius, cx-radius:cx+radius][index] = 0
plt.imshow(croped_img)

croped_img=cv2.cvtColor(croped_img, cv2.COLOR_BGR2RGB)
cv2.imwrite('croped_circle_2.jpg', croped_img)

Tags: imgindexpltcv2colorjpgcximshow
1条回答
网友
1楼 · 发布于 2024-04-19 03:16:16

一种方法是创建一个文本掩码,并使用它进行修复。在Python/OpenCV中,有两种形式的修复:Telea和Navier-Stokes。两者产生的结果大致相同

输入:

enter image description here

import cv2
import numpy as np

# read input
img = cv2.imread('circle_text.png')

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold and invert
thresh = cv2.threshold(gray, 155, 255, cv2.THRESH_BINARY)[1]

# apply morphology close
kernel = np.ones((3,3), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_DILATE, kernel)

# get contours and filter to keep only small regions
mask = np.zeros_like(gray, dtype=np.uint8)
cntrs = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
for c in cntrs:
    area = cv2.contourArea(c)
    if area < 1000:
        cv2.drawContours(mask,[c],0,255,-1)

# do inpainting
result1 = cv2.inpaint(img,mask,3,cv2.INPAINT_TELEA)
result2 = cv2.inpaint(img,mask,3,cv2.INPAINT_NS)

# save results
cv2.imwrite('circle_text_threshold.png', thresh)
cv2.imwrite('circle_text_mask.png', mask)
cv2.imwrite('circle_text_inpainted_telea.png', result1)
cv2.imwrite('circle_text_inpainted_ns.png', result2)

# show results
cv2.imshow('thresh',thresh)
cv2.imshow('mask',mask)
cv2.imshow('result1',result1)
cv2.imshow('result2',result2)
cv2.waitKey(0)
cv2.destroyAllWindows()

阈值图像:

enter image description here

遮罩图像:

enter image description here

Telea修复:

enter image description here

Navier Stokes修复:

enter image description here

相关问题 更多 >