Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small updates for Python 3.9 (and OpenCV 4.5) compatibility #25

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion derive_cubic.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
num_beta = 0.03

for key in [a, b, c, d]:
print key, '=', S[key]
print(key, '=', S[key])
coeffs.append(S[key].subs(dict(alpha=num_alpha,
beta=num_beta)))

Expand Down
95 changes: 51 additions & 44 deletions page_dewarp.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
# for some reason pylint complains about cv2 members being undefined :(
# pylint: disable=E1101

PAGE_MARGIN_X = 50 # reduced px to ignore near L/R edge
PAGE_MARGIN_Y = 20 # reduced px to ignore near T/B edge
PAGE_MARGIN_X = 0 # reduced px to ignore near L/R edge
PAGE_MARGIN_Y = 0 # reduced px to ignore near T/B edge

OUTPUT_ZOOM = 1.0 # how much to zoom output relative to *original* image
OUTPUT_DPI = 300 # just affects stated DPI of PNG, not appearance
Expand Down Expand Up @@ -234,7 +234,6 @@ def project_keypoints(pvec, keypoint_index):


def resize_to_screen(src, maxw=1280, maxh=700, copy=False):

height, width = src.shape[:2]

scl_x = float(width)/maxw
Expand Down Expand Up @@ -347,10 +346,13 @@ def blob_mean_and_tangent(contour):
moments = cv2.moments(contour)

area = moments['m00']


if area == 0.:
raise ValueError

mean_x = moments['m10'] / area
mean_y = moments['m01'] / area

moments_matrix = np.array([
[moments['mu20'], moments['mu11']],
[moments['mu11'], moments['mu02']]
Expand All @@ -371,7 +373,7 @@ def __init__(self, contour, rect, mask):
self.contour = contour
self.rect = rect
self.mask = mask

self.center, self.tangent = blob_mean_and_tangent(contour)

self.angle = np.arctan2(self.tangent[1], self.tangent[0])
Expand Down Expand Up @@ -446,27 +448,32 @@ def get_contours(name, small, pagemask, masktype):

mask = get_mask(name, small, pagemask, masktype)

_, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)

contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)
contours_out = []

for contour in contours:

rect = cv2.boundingRect(contour)
xmin, ymin, width, height = rect

if (width < TEXT_MIN_WIDTH or
height < TEXT_MIN_HEIGHT or
width < TEXT_MIN_ASPECT*height):
continue

tight_mask = make_tight_mask(contour, xmin, ymin, width, height)

if tight_mask.sum(axis=0).max() > TEXT_MAX_THICKNESS:
continue

contours_out.append(ContourInfo(contour, rect, tight_mask))

try:
next_contour = ContourInfo(contour, rect, tight_mask)
except ValueError:
print("This contour has zero area, dropping.")
else:
contours_out.append(next_contour)

if DEBUG_LEVEL >= 2:
visualize_contours(name, small, contours_out)
Expand Down Expand Up @@ -550,12 +557,12 @@ def sample_spans(shape, spans):
yvals = np.arange(cinfo.mask.shape[0]).reshape((-1, 1))
totals = (yvals * cinfo.mask).sum(axis=0)
means = totals / cinfo.mask.sum(axis=0)

xmin, ymin = cinfo.rect[:2]

step = SPAN_PX_PER_STEP
start = ((len(means)-1) % step) / 2

start = ((len(means)-1) % step) // 2
contour_points += [(x+xmin, means[x]+ymin)
for x in range(start, len(means), step)]

Expand Down Expand Up @@ -736,20 +743,20 @@ def objective(pvec):
ppts = project_keypoints(pvec, keypoint_index)
return np.sum((dstpoints - ppts)**2)

print ' initial objective is', objective(params)
print(' initial objective is', objective(params))

if DEBUG_LEVEL >= 1:
projpts = project_keypoints(params, keypoint_index)
display = draw_correspondences(small, dstpoints, projpts)
debug_show(name, 4, 'keypoints before', display)

print ' optimizing', len(params), 'parameters...'
print(' optimizing', len(params), 'parameters...')
start = datetime.datetime.now()
res = scipy.optimize.minimize(objective, params,
method='Powell')
end = datetime.datetime.now()
print ' optimization took', round((end-start).total_seconds(), 2), 'sec.'
print ' final objective is', res.fun
print(' optimization took', round((end-start).total_seconds(), 2), 'sec.')
print(' final objective is', res.fun)
params = res.x

if DEBUG_LEVEL >= 1:
Expand All @@ -773,7 +780,7 @@ def objective(dims):
res = scipy.optimize.minimize(objective, dims, method='Powell')
dims = res.x

print ' got page dims', dims[0], 'x', dims[1]
print(' got page dims', dims[0], 'x', dims[1])

return dims

Expand All @@ -785,12 +792,12 @@ def remap_image(name, img, small, page_dims, params):

width = round_nearest_multiple(height * page_dims[0] / page_dims[1],
REMAP_DECIMATE)

print ' output will be {}x{}'.format(width, height)

height_small = height / REMAP_DECIMATE
width_small = width / REMAP_DECIMATE

print(' output will be {}x{}'.format(width, height))
height_small = height // REMAP_DECIMATE
width_small = width // REMAP_DECIMATE
page_x_range = np.linspace(0, page_dims[0], width_small)
page_y_range = np.linspace(0, page_dims[1], height_small)

Expand Down Expand Up @@ -841,7 +848,8 @@ def remap_image(name, img, small, page_dims, params):
def main():

if len(sys.argv) < 2:
print 'usage:', sys.argv[0], 'IMAGE1 [IMAGE2 ...]'
print('usage:', sys.argv[0], 'IMAGE1 [IMAGE2 ...]')
print("\nFor the Python 3-ified version, make sure you have `opencv-python` installed (pip install opencv-python).")
sys.exit(0)

if DEBUG_LEVEL > 0 and DEBUG_OUTPUT != 'file':
Expand All @@ -856,8 +864,8 @@ def main():
basename = os.path.basename(imgfile)
name, _ = os.path.splitext(basename)

print 'loaded', basename, 'with size', imgsize(img),
print 'and resized to', imgsize(small)
print('loaded', basename, 'with size', imgsize(img), end=" ")
print('and resized to', imgsize(small))

if DEBUG_LEVEL >= 3:
debug_show(name, 0.0, 'original', small)
Expand All @@ -867,21 +875,21 @@ def main():
cinfo_list = get_contours(name, small, pagemask, 'text')
spans = assemble_spans(name, small, pagemask, cinfo_list)

if len(spans) < 3:
print ' detecting lines because only', len(spans), 'text spans'
if len(spans) < 10:
print(' detecting lines because only', len(spans), 'text spans')
cinfo_list = get_contours(name, small, pagemask, 'line')
spans2 = assemble_spans(name, small, pagemask, cinfo_list)
if len(spans2) > len(spans):
spans = spans2

if len(spans) < 1:
print 'skipping', name, 'because only', len(spans), 'spans'
if len(spans) < 5:
print('skipping', name, 'because only', len(spans), 'spans')
continue

span_points = sample_spans(small.shape, spans)

print ' got', len(spans), 'spans',
print 'with', sum([len(pts) for pts in span_points]), 'points.'
print(' got', len(spans), 'spans ', end="")
print('with', sum([len(pts) for pts in span_points]), 'points.')

corners, ycoords, xcoords = keypoints_from_samples(name, small,
pagemask,
Expand All @@ -904,11 +912,10 @@ def main():

outfiles.append(outfile)

print ' wrote', outfile
print
print(' wrote', outfile, '\n')

print 'to convert to PDF (requires ImageMagick):'
print ' convert -compress Group4 ' + ' '.join(outfiles) + ' output.pdf'
print('to convert to PDF (requires ImageMagick):')
print(' convert -compress Group4 ' + ' '.join(outfiles) + ' output.pdf')


if __name__ == '__main__':
Expand Down