Converts a print existing in a photo into an image cropped from directly above. You can convert the upper photo to the lower photo.
--Since it is converted to a vertically long A4 file, rewrite x and y in the case of landscape. --Since x is the length of the short side, rewrite it appropriately.
cutting_a4.py
#Receive a color image, cut out the paper and return it
def cutting_paper(img):
x = 2000 #X coordinate after cutting
y = int(x*1.415)
img_gray = gray(img)
#Binarization
ret,img_th1 = cv2.threshold(img_gray,220,255,cv2.THRESH_TOZERO_INV)
img_not = cv2.bitwise_not(img_th1)
ret,img_th2 = cv2.threshold(img_not,0,255, cv2.THRESH_BINARY | cv2.THRESH_OTSU )
#Contour extraction
contours, hierarchy = cv2.findContours(img_th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#The second largest square is the outline of the paper, so paper_Take out tap
pic_tap = None #Image contour
paper_tap = None #Paper contour
for i, con in enumerate(contours):
size = cv2.contourArea(con)
if pic_tap is None:
pic_tap = (con,size)
continue
if pic_tap[1] <= size:
pic_tap = (con,size)
continue
elif paper_tap is None:
paper_tap = (con,size)
elif paper_tap[1] <= size:
paper_tap = (con,size)
#Approximate straight line and draw
epsilon = 0.1*cv2.arcLength(paper_tap[0],True)
paper_corners= cv2.approxPolyDP(paper_tap[0],epsilon,True)#Paper vertex coordinates
fix_con = np.array([[[0,0]],[[x,0]],[[x,y]],[[0,y]]], dtype="int32")#Size after shaping
M = cv2.getPerspectiveTransform(np.float32(paper_corners),np.float32(fix_con))#Generation of transformation matrix
img_trans = cv2.warpPerspective(img,M,(x,y))#conversion
return img_trans
img = cv2.imread('input.png',-1)
cv2.imwrite("output.png ", img)
plt.imshow(plt.imread("output.png "))
Recommended Posts