edge_finder.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env python2
  2. import numpy as np
  3. import sys
  4. import cv2
  5. cv_version = int(cv2.__version__.split('.')[0])
  6. GRAY = cv2.CV_LOAD_IMAGE_GRAYSCALE if cv_version == 2 else cv2.IMREAD_GRAYSCALE
  7. COLOR = cv2.CV_LOAD_IMAGE_COLOR if cv_version == 2 else cv2.IMREAD_COLOR
  8. def show(img):
  9. #cv2.namedWindow("immagine",cv2.WINDOW_AUTOSIZE)
  10. cv2.imshow("immagine", img)
  11. cv2.waitKey(0)
  12. def contourIndex(lista):
  13. # ritorna l'indice del contorno con perimetro maggiore
  14. val=-1
  15. index=0
  16. for num, cont in enumerate(lista):
  17. value=cv2.arcLength(cont,True)
  18. if val<value:
  19. val=value
  20. index=num
  21. return index
  22. img=cv2.imread(sys.argv[1], GRAY)
  23. #img=cv2.imread(sys.argv[1],cv2.CV_LOAD_IMAGE_COLOR)
  24. #la riga successiva serve a rendere visualizzabile l immagine sul nostro pc
  25. #img=cv2.resize(img,(350,262))
  26. #assumendo che il background e nero nelle condizioni attuali (27/12/2016) del bookscanner il valore buono e 100 (su 255)
  27. buono=100
  28. mask=cv2.inRange(img,buono,255)
  29. if cv_version == 2:
  30. contorni, hier = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  31. else:
  32. _, contorni, hier = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  33. bianco=np.zeros(mask.shape,dtype=np.uint8) # crea un coso nero
  34. # indexImportante indica il contorno piu grande, che crediamo sia quello del libro
  35. indexImportante=contourIndex(contorni)
  36. cv2.drawContours(img,contorni,indexImportante,255,thickness=3)
  37. cv2.fillPoly(bianco,[contorni[indexImportante]], 255)
  38. img=cv2.imread(sys.argv[1], COLOR)
  39. img = cv2.bitwise_and(img, img, mask=bianco)
  40. if len(sys.argv) > 2:
  41. cv2.imwrite(sys.argv[2], img)
  42. else:
  43. show(img)
  44. # vim: set ts=4 sw=4 et: