1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- #!/usr/bin/env python2
- import numpy as np
- import sys
- import cv2
- cv_version = int(cv2.__version__.split('.')[0])
- GRAY = cv2.CV_LOAD_IMAGE_GRAYSCALE if cv_version == 2 else cv2.IMREAD_GRAYSCALE
- COLOR = cv2.CV_LOAD_IMAGE_COLOR if cv_version == 2 else cv2.IMREAD_COLOR
- def show(img):
- #cv2.namedWindow("immagine",cv2.WINDOW_AUTOSIZE)
- cv2.imshow("immagine", img)
- cv2.waitKey(0)
- def contourIndex(lista):
- # ritorna l'indice del contorno con perimetro maggiore
- val=-1
- index=0
- for num, cont in enumerate(lista):
- value=cv2.arcLength(cont,True)
- if val<value:
- val=value
- index=num
- return index
- img=cv2.imread(sys.argv[1], GRAY)
- #img=cv2.imread(sys.argv[1],cv2.CV_LOAD_IMAGE_COLOR)
- #la riga successiva serve a rendere visualizzabile l immagine sul nostro pc
- #img=cv2.resize(img,(350,262))
- #assumendo che il background e nero nelle condizioni attuali (27/12/2016) del bookscanner il valore buono e 100 (su 255)
- buono=100
- mask=cv2.inRange(img,buono,255)
- if cv_version == 2:
- contorni, hier = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- else:
- _, contorni, hier = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- bianco=np.zeros(mask.shape,dtype=np.uint8) # crea un coso nero
- # indexImportante indica il contorno piu grande, che crediamo sia quello del libro
- indexImportante=contourIndex(contorni)
- cv2.drawContours(img,contorni,indexImportante,255,thickness=3)
- cv2.fillPoly(bianco,[contorni[indexImportante]], 255)
- img=cv2.imread(sys.argv[1], COLOR)
- img = cv2.bitwise_and(img, img, mask=bianco)
- if len(sys.argv) > 2:
- cv2.imwrite(sys.argv[2], img)
- else:
- show(img)
- # vim: set ts=4 sw=4 et:
|