Browse Source

python cv3 compatibility

boyska 7 years ago
parent
commit
fc6cffe2ba
1 changed files with 16 additions and 7 deletions
  1. 16 7
      edge_finder.py

+ 16 - 7
edge_finder.py

@@ -3,13 +3,19 @@
 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.namedWindow("immagine",cv2.WINDOW_AUTOSIZE)
+    cv2.imshow("immagine", img)
     cv2.waitKey(0)
 
+
 def contourIndex(lista):
-# ritorna l'indice del contorno con perimetro maggiore
+    # ritorna l'indice del contorno con perimetro maggiore
     val=-1
     index=0
     for num, cont in enumerate(lista):
@@ -19,14 +25,17 @@ def contourIndex(lista):
             index=num 
     return index
 
-img=cv2.imread(sys.argv[1],cv2.CV_LOAD_IMAGE_GRAYSCALE)
+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)
-contorni, hier =cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
+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
@@ -34,10 +43,10 @@ indexImportante=contourIndex(contorni)
 cv2.drawContours(img,contorni,indexImportante,255,thickness=3)
 cv2.fillPoly(bianco,[contorni[indexImportante]], 255)
 
-img=cv2.imread(sys.argv[1],cv2.CV_LOAD_IMAGE_COLOR)
+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)
+    cv2.imwrite(sys.argv[2], img)
 else:
     show(img)