ultimate-photo-digitizer/extract_photos.py
2023-07-23 11:57:38 +02:00

68 lines
1.6 KiB
Python

# import required libraries
import cv2
import sys
# read the input image
img = cv2.imread('hires_test.png')
if not img:
print("unable to read image")
sys.exit(-1)
print("read done")
# convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print("convert to gray done")
# apply thresholding on the gray image to create a binary image
ret,thresh = cv2.threshold(gray,127,255,0)
# find the contours
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
areas = list()
for cnt in contours:
#print(cv2.contourArea(cnt))
areas.append(cv2.contourArea(cnt))
areas.sort(reverse=True)
#print(areas)
if (len(areas) >= 5):
outer = areas[0]
inter_min = areas[4]
print("Outer area: " + str(outer))
print("Inner area: " + str(inter_min))
index = 0
for cnt in contours:
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)
# draw the bounding rectangle
#imgView = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
x = x + 5
y = y + 5
w = w - 10
h = h - 10
crop_img = img[y:y+h, x:x+w]
#cv2.imshow("cropped", crop_img)
cv2.imwrite("export_"+str(index)+".png", crop_img)
index = index + 1
#cv2.waitKey(0)
# display the image with bounding rectangle drawn on it
#imgDownscaled = cv2.resize(imgView, (410, 876))
#cv2.imshow("Bounding Rectangle", imgDownscaled)
#cv2.waitKey(0)
#cv2.destroyAllWindows()