crop image based on percentage

This commit is contained in:
Hendrik Schutter 2023-07-25 20:26:32 +02:00
parent cf8c3c8263
commit 237aa6cc18

View File

@ -10,6 +10,9 @@ import subprocess
number_of_photos_in_scan = 3
crop_height = 2.0 # offset in percent
crop_width = 2.0 # offset in percent
def convert_to_avif(input_dir, output_dir):
# print("input: " + str(input))
# print("output: " + str(output))
@ -76,14 +79,15 @@ def auto_crop_scan(src_path, output_dir):
area = cv2.contourArea(cnt)
if (area < outer) and (area >= inter_min):
# compute the bounding rectangle of the contour
x, y, w, h = cv2.boundingRect(cnt)
pos_x, pos_y, width, height = cv2.boundingRect(cnt)
x = x + 5 # TODO
y = y + 5 # TODO
w = w - 10 # TODO
h = h - 10 # TODO
cropped_width = int(width - ((width/100.0*crop_width)))
cropped_pos_x = int(pos_x + ((width-cropped_width)/2.0))
img_crop = img_src[y : y + h, x : x + w]
cropped_height = int(height - ((height/100.0*crop_height)))
cropped_pos_y = int(pos_y + ((height-cropped_height)/2.0))
img_crop = img_src[cropped_pos_y : cropped_pos_y + cropped_height, cropped_pos_x : cropped_pos_x + cropped_width]
if img_crop is None:
raise Exception("unable to crop image")
@ -99,6 +103,7 @@ def auto_crop_scan(src_path, output_dir):
cv2.imwrite(export_file_path, img_crop)
index = index + 1
break
else:
raise Exception("unable to find all photos in scan")
@ -129,21 +134,21 @@ def main():
for path in os.listdir(source_dir_path):
if os.path.isfile(os.path.join(source_dir_path, path)):
print("Found scan: " + str(os.path.join(source_dir_path, path)), end="")
print("Found scan: " + str(os.path.join(source_dir_path, path)), end=" ")
try:
auto_crop_scan(os.path.join(source_dir_path, path), tmp_dir_path)
convert_to_avif(tmp_dir_path, destination_dir_path)
print("Successfully extracted photos from scan")
print(" Successfully extracted photos from scan")
except Exception as e:
print(str(e))
failed_extractions = failed_extractions + 1
if(failed_extractions == 0):
print("Exiting without error")
print("\nExiting without error")
sys.exit(0)
else:
print("Unable to extract " + str(failed_extractions) + " scans.")
print("Exiting with error")
print("\nExiting with error")
sys.exit(-1)
if __name__ == "__main__":