43 lines
1.1 KiB
Python
43 lines
1.1 KiB
Python
from itertools import count
|
|
|
|
import cv2
|
|
import imutils
|
|
import numpy as np
|
|
import pdf2image
|
|
from matplotlib import pyplot as plt
|
|
|
|
|
|
def parse(image: np.array):
|
|
gray = ~cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
|
blurred = cv2.GaussianBlur(gray, (5, 5), 1)
|
|
thresh = cv2.threshold(blurred, 253, 255, cv2.THRESH_BINARY)[1]
|
|
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
|
cnts = imutils.grab_contours(cnts)
|
|
|
|
for c in cnts:
|
|
peri = cv2.arcLength(c, True)
|
|
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
|
|
yield cv2.boundingRect(approx)
|
|
|
|
|
|
def annotate_boxes(image, rects):
|
|
for rect in rects:
|
|
(x, y, w, h) = rect
|
|
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
|
|
|
|
return image
|
|
|
|
|
|
def annotate_boxes_in_pdf(pdf_path, page_index=1):
|
|
|
|
page = pdf2image.convert_from_path(pdf_path, first_page=page_index + 1, last_page=page_index + 1)[0]
|
|
page = np.array(page)
|
|
|
|
asd = parse(page)
|
|
page = annotate_boxes(page, asd)
|
|
|
|
fig, ax = plt.subplots(1, 1)
|
|
fig.set_size_inches(20, 20)
|
|
ax.imshow(page)
|
|
plt.show()
|