import cv2 import time import logging d = 1 while True: try: threshold = 25 time.sleep(1) input = ('input%d.jpg'%d) page = ('page%d.jpg'%d) print("Value of d is:",d,"\n","Page name:",input) img = cv2.imread(input, 0) # load grayscale version # the indeces where the useful region starts and ends hStrart = 0 hEnd = img.shape[0] vStart = 0 vEnd = img.shape[1] # get row and column maxes for each row and column hMax = img.max(1) vMax = img.max(0) hDone_flag = False vDone_flag = False # go through the list of max and begin where the pixel value is greater # than the threshold for i in range(hMax.size): if not hDone_flag: if hMax[i] > threshold: hStart = i hDone_flag = True if hDone_flag: if hMax[i] < threshold: hEnd = i break for i in range(vMax.size): if not vDone_flag: if vMax[i] > threshold: vStart = i vDone_flag = True if vDone_flag: if vMax[i] < threshold: vEnd = i break # load the color image and choose only the useful area from it img2 = (cv2.imread(input))[hStart:hEnd, vStart:vEnd,:] # write the cropped image cv2.imwrite(page, img2) d+=1 print("Value of d is:", d) except: logging.exception("message") print("All pages must be ready!") break