Created
August 13, 2023 21:15
-
-
Save daisycamber/5c0c53511cef44bec44c6d8d050b1c39 to your computer and use it in GitHub Desktop.
Censor text in an image with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2, pytesseract | |
import numpy as np | |
AVERAGE = 100 | |
EXTRA = 1 | |
MIN_TEXT = 4 | |
def censor_image(input_file): | |
image = cv2.imread(input_file) | |
transparent_img = np.zeros((image.shape[0], image.shape[1], image.shape[2]), dtype=np.uint8) | |
data = pytesseract.image_to_data(image, output_type='dict') | |
boxes = len(data['level']) | |
for i in range(boxes): | |
if len(data['text']) < MIN_TEXT: continue | |
(x, y, w, h) = (data['left'][i], data['top'][i], data['width'][i], data['height'][i]) | |
x = x - w * extra | |
y = y - h * extra | |
w = w * extra * 3 | |
h = h * extra * 3 | |
if x < 0: x = 0 | |
if y < 0: y = 0 | |
if y + h > image.shape[0]: y = image.shape[0] - h | |
if x + w > image.shape[1]: x = image.shape[1] - w | |
img = cv2.blur(image[y:y+h, x:x+w], (AVERAGE, AVERAGE)) | |
image[y:y+h, x:x+w] = img | |
cv2.imwrite(input_file, image) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment