├── .gitattributes ├── .gitignore ├── Official_Tutorial_Python_Codes ├── 1_introduction │ ├── display_image.py │ └── modify_image.py ├── 2_core │ ├── BasicLinearTransforms.py │ ├── add_images.py │ └── fiter2d.py ├── 3_imgproc │ ├── border.py │ ├── boundingrect.py │ ├── canny.py │ ├── comparehist.py │ ├── convexhull.py │ ├── equalizehist.py │ ├── findcontours.py │ ├── geometric_transform.py │ ├── histogram1d.py │ ├── houghcircles.py │ ├── houghlines.py │ ├── laplacian.py │ ├── linear_filter.py │ ├── minarearect.py │ ├── moments.py │ ├── morphology_1.py │ ├── pointpolygontest.py │ ├── pyramids.py │ ├── remap.py │ ├── smoothing.py │ ├── sobel.py │ └── templatematching.py └── README ├── OpenCV_Python_Blog ├── kmeans_clustering │ └── kmeans_data.txt └── sudoku_v_0.0.6 │ ├── .picasa.ini │ ├── README.txt │ ├── feature_vector_pixels.data │ ├── perfect.py │ ├── sampleout.jpg │ ├── samples_pixels.data │ ├── sudoku.jpg │ └── sudoku.py └── README /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | ################# 3 | ## Eclipse 4 | ################# 5 | 6 | *.pydevproject 7 | .project 8 | .metadata 9 | bin/** 10 | tmp/** 11 | tmp/**/* 12 | *.tmp 13 | *.bak 14 | *.swp 15 | *~.nib 16 | local.properties 17 | .classpath 18 | .settings/ 19 | .loadpath 20 | 21 | # External tool builders 22 | .externalToolBuilders/ 23 | 24 | # Locally stored "Eclipse launch configurations" 25 | *.launch 26 | 27 | # CDT-specific 28 | .cproject 29 | 30 | # PDT-specific 31 | .buildpath 32 | 33 | 34 | ################# 35 | ## Visual Studio 36 | ################# 37 | 38 | ## Ignore Visual Studio temporary files, build results, and 39 | ## files generated by popular Visual Studio add-ons. 40 | 41 | # User-specific files 42 | *.suo 43 | *.user 44 | *.sln.docstates 45 | 46 | # Build results 47 | **/[Dd]ebug/ 48 | **/[Rr]elease/ 49 | *_i.c 50 | *_p.c 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.vspscc 65 | .builds 66 | **/*.dotCover 67 | 68 | ## TODO: If you have NuGet Package Restore enabled, uncomment this 69 | #**/packages/ 70 | 71 | # Visual C++ cache files 72 | ipch/ 73 | *.aps 74 | *.ncb 75 | *.opensdf 76 | *.sdf 77 | 78 | # Visual Studio profiler 79 | *.psess 80 | *.vsp 81 | 82 | # ReSharper is a .NET coding add-in 83 | _ReSharper* 84 | 85 | # Installshield output folder 86 | [Ee]xpress 87 | 88 | # DocProject is a documentation generator add-in 89 | DocProject/buildhelp/ 90 | DocProject/Help/*.HxT 91 | DocProject/Help/*.HxC 92 | DocProject/Help/*.hhc 93 | DocProject/Help/*.hhk 94 | DocProject/Help/*.hhp 95 | DocProject/Help/Html2 96 | DocProject/Help/html 97 | 98 | # Click-Once directory 99 | publish 100 | 101 | # Others 102 | [Bb]in 103 | [Oo]bj 104 | sql 105 | TestResults 106 | *.Cache 107 | ClientBin 108 | stylecop.* 109 | ~$* 110 | *.dbmdl 111 | Generated_Code #added for RIA/Silverlight projects 112 | 113 | # Backup & report files from converting an old project file to a newer 114 | # Visual Studio version. Backup files are not needed, because we have git ;-) 115 | _UpgradeReport_Files/ 116 | Backup*/ 117 | UpgradeLog*.XML 118 | 119 | 120 | 121 | ############ 122 | ## Windows 123 | ############ 124 | 125 | # Windows image file caches 126 | Thumbs.db 127 | 128 | # Folder config file 129 | Desktop.ini 130 | 131 | 132 | ############# 133 | ## Python 134 | ############# 135 | 136 | *.py[co] 137 | 138 | # Packages 139 | *.egg 140 | *.egg-info 141 | dist 142 | build 143 | eggs 144 | parts 145 | bin 146 | var 147 | sdist 148 | develop-eggs 149 | .installed.cfg 150 | 151 | # Installer logs 152 | pip-log.txt 153 | 154 | # Unit test / coverage reports 155 | .coverage 156 | .tox 157 | 158 | #Translations 159 | *.mo 160 | 161 | #Mr Developer 162 | .mr.developer.cfg 163 | 164 | # Mac crap 165 | .DS_Store 166 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/1_introduction/display_image.py: -------------------------------------------------------------------------------- 1 | ''' filename : display_image.py 2 | 3 | Description : This sample demonstrates how to read an image, display it on the window and print image size. 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/introduction/display_image/display_image.html#display-image 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to load image and display it in window 10 | 11 | Usage : python display_image.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import sys 17 | import numpy as np 18 | 19 | if len(sys.argv)!=2: ## Check for error in usage syntax 20 | print "Usage : python display_image.py " 21 | 22 | else: 23 | img = cv2.imread(sys.argv[1],cv2.CV_LOAD_IMAGE_COLOR) ## Read image file 24 | 25 | if (img == None): ## Check for invalid input 26 | print "Could not open or find the image" 27 | else: 28 | cv2.namedWindow('Display Window') ## create window for display 29 | cv2.imshow('Display Window',img) ## Show image in the window 30 | print "size of image: ",img.shape ## print size of image 31 | cv2.waitKey(0) ## Wait for keystroke 32 | cv2.destroyAllWindows() ## Destroy all windows 33 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/1_introduction/modify_image.py: -------------------------------------------------------------------------------- 1 | ''' file name : modify_image.py 2 | 3 | Description : This sample shows how to convert a color image to grayscale and save it into disk 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/introduction/load_save_image/load_save_image.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn 1) to convert RGB image to grayscale, 2) save image to disk 10 | 11 | Usage : python modify_image.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | import sys 18 | 19 | image = cv2.imread('lena.jpg') # change image name as you need or give sys.argv[1] to read from command line 20 | gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert image to gray 21 | 22 | cv2.imwrite('gray_image.jpg',gray_image) # saves gray image to disk 23 | 24 | cv2.imshow('color_image',image) 25 | cv2.imshow('gray_image',gray_image) 26 | 27 | cv2.waitKey(0) 28 | cv2.destroyAllWindows() 29 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/2_core/BasicLinearTransforms.py: -------------------------------------------------------------------------------- 1 | ''' file name : BasicLinearTransforms.py 2 | 3 | Description : This sample shows how apply an equation on an image, g(x) = alpha*i(x) + beta 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn use of basic matrix operations in OpenCV and how they differ from corresponding numpy operations 10 | 11 | Usage : python BasicLinearTransforms.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | 19 | alpha = float(input('* Enter the alpha value [1.0-3.0]: ')) # Simple contrast control 20 | beta = int(input('Enter the beta value [0-100]: ')) # Simple brightness control 21 | 22 | print " Basic Linear Transforms " 23 | print "-----------------------------" 24 | 25 | img = cv2.imread('lena.jpg') 26 | 27 | mul_img = cv2.multiply(img,np.array([alpha])) # mul_img = img*alpha 28 | new_img = cv2.add(mul_img,np.array([beta])) # new_img = img*alpha + beta 29 | 30 | cv2.imshow('original_image', img) 31 | cv2.imshow('new_image',new_img) 32 | 33 | cv2.waitKey(0) 34 | cv2.destroyAllWindows() 35 | 36 | ## NB : Please visit for more details: http://opencvpython.blogspot.com/2012/06/difference-between-matrix-arithmetic-in.html 37 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/2_core/add_images.py: -------------------------------------------------------------------------------- 1 | ''' file name : simple_linear_blender.py 2 | 3 | Discription : This sample shows how to blend two images. 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/core/adding_images/adding_images.html#adding-images 6 | 7 | Level : Beginner 8 | 9 | Benefits : 1) Learns usage of cv2.addWeighted and 2) its numpy implementation 10 | 11 | Usage : python simple_linear_blender.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | print ''' Simple Linear Blender 19 | ------------------------------------------ 20 | 21 | Enter value of alpha [0:1] :''' 22 | 23 | alpha = float(input()) # Ask the value of alpha 24 | 25 | if 0<=alpha<=1: # Check if 0<= alpha <=1 26 | beta = 1.0 - alpha # Calculate beta = 1 - alpha 27 | gamma = 0.0 # parameter gamma = 0 28 | 29 | img1 = cv2.imread('lena.jpg') 30 | img2 = cv2.imread('res.jpg') 31 | 32 | if img1==None: 33 | print "img1 not ready" 34 | elif img2==None: 35 | print "img2 not ready" 36 | else: 37 | dst = cv2.addWeighted(img1,alpha,img2,beta,gamma) # Get weighted sum of img1 and img2 38 | #dst = np.uint8(alpha*(img1)+beta*(img2)) # This is simple numpy version of above line. But cv2 function is around 2x faster 39 | cv2.imshow('dst',dst) 40 | cv2.waitKey(0) 41 | cv2.destroyAllWindows() 42 | else: 43 | print "value of alpha should be 0 and 1" 44 | 45 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/2_core/fiter2d.py: -------------------------------------------------------------------------------- 1 | ''' file name : filter2d.py 2 | 3 | Description : This sample shows how to filter/convolve an image with a kernel 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/core/mat-mask-operations/mat-mask-operations.html#the-filter2d-function 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to convolve with cv2.filter2D function 10 | 11 | Usage : python filter2d.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | img = cv2.imread('lena.jpg') 19 | 20 | kernel = np.array([ [0,-1,0], 21 | [-1,5,-1], 22 | [0,-1,0] ],np.float32) # kernel should be floating point type. 23 | 24 | new_img = cv2.filter2D(img,-1,kernel) # ddepth = -1, means destination image has depth same as input image. 25 | 26 | cv2.imshow('img',img) 27 | cv2.imshow('new',new_img) 28 | 29 | cv2.waitKey(0) 30 | cv2.destroyAllWindows() 31 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/border.py: -------------------------------------------------------------------------------- 1 | ''' file name : border.py 2 | 3 | Description : This sample shows how to add border to an image 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/copyMakeBorder/copyMakeBorder.html#copymakebordertutorial 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use cv2.copyMakeBorder() 10 | 11 | Usage : python border.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | print " Press r to replicate the border with a random color " 19 | print " Press c to replicate the border " 20 | print " Press Esc to exit " 21 | 22 | img = cv2.imread('home.jpg') 23 | rows,cols = img.shape[:2] 24 | 25 | dst = img.copy() 26 | 27 | top = int (0.05*rows) 28 | bottom = int (0.05*rows) 29 | 30 | left = int (0.05*cols) 31 | right = int (0.05*cols) 32 | 33 | while(True): 34 | 35 | cv2.imshow('border',dst) 36 | k = cv2.waitKey(500) 37 | 38 | if k==27: 39 | break 40 | elif k == ord('c'): 41 | value = np.random.randint(0,255,(3,)).tolist() 42 | dst = cv2.copyMakeBorder(img,top,bottom,left,right,cv2.BORDER_CONSTANT,value = value) 43 | elif k == ord('r'): 44 | dst = cv2.copyMakeBorder(img,top,bottom,left,right,cv2.BORDER_REPLICATE) 45 | 46 | cv2.destroyAllWindows() 47 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/boundingrect.py: -------------------------------------------------------------------------------- 1 | ''' file name : boundingrect.py 2 | 3 | Description : This sample shows how to find the bounding rectangle and minimum enclosing circle of a contour 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html 6 | Level : Beginner 7 | 8 | Benefits : Learn to use 1) cv2.boundingRect() and 2) cv2.minEnclosingCircle() 9 | 10 | Usage : python boundingrect.py 11 | 12 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials''' 13 | 14 | import cv2 15 | import numpy as np 16 | 17 | def thresh_callback(thresh): 18 | edges = cv2.Canny(blur,thresh,thresh*2) 19 | drawing = np.zeros(img.shape,np.uint8) # Image to draw the contours 20 | contours,hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 21 | for cnt in contours: 22 | bx,by,bw,bh = cv2.boundingRect(cnt) 23 | (cx,cy),radius = cv2.minEnclosingCircle(cnt) 24 | cv2.drawContours(drawing,[cnt],0,(0,255,0),1) # draw contours in green color 25 | cv2.circle(drawing,(int(cx),int(cy)),int(radius),(0,0,255),2) # draw circle in red color 26 | cv2.rectangle(drawing,(bx,by),(bx+bw,by+bh),(255,0,0),3) # draw rectangle in blue color) 27 | cv2.imshow('output',drawing) 28 | cv2.imshow('input',img) 29 | 30 | img = cv2.imread('messi5.jpg') 31 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 32 | blur = cv2.GaussianBlur(gray,(5,5),0) 33 | 34 | cv2.namedWindow('input') 35 | 36 | thresh = 100 37 | max_thresh = 255 38 | 39 | cv2.createTrackbar('canny thresh:','input',thresh,max_thresh,thresh_callback) 40 | 41 | thresh_callback(0) 42 | 43 | if cv2.waitKey(0) == 27: 44 | cv2.destroyAllWindows() 45 | 46 | ### For more details & feature extraction on contours, visit : http://opencvpython.blogspot.com/2012/04/contour-features.html 47 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/canny.py: -------------------------------------------------------------------------------- 1 | ''' file name : canny.py 2 | 3 | Description : This sample shows how to find edges using canny edge detection 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/canny_detector/canny_detector.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to apply canny edge detection to images. 10 | 11 | Usage : python canny.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | 16 | import cv2 17 | import numpy as np 18 | 19 | def CannyThreshold(lowThreshold): 20 | detected_edges = cv2.GaussianBlur(gray,(3,3),0) 21 | detected_edges = cv2.Canny(detected_edges,lowThreshold,lowThreshold*ratio,apertureSize = kernel_size) 22 | dst = cv2.bitwise_and(img,img,mask = detected_edges) # just add some colours to edges from original image. 23 | cv2.imshow('canny demo',dst) 24 | 25 | lowThreshold = 0 26 | max_lowThreshold = 100 27 | ratio = 3 28 | kernel_size = 3 29 | 30 | img = cv2.imread('messi5.jpg') 31 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 32 | 33 | cv2.namedWindow('canny demo') 34 | 35 | cv2.createTrackbar('Min threshold','canny demo',lowThreshold, max_lowThreshold, CannyThreshold) 36 | 37 | CannyThreshold(0) # initialization 38 | if cv2.waitKey(0) == 27: 39 | cv2.destroyAllWindows() 40 | 41 | # visit for output results : http://opencvpython.blogspot.com/2012/06/image-derivatives-sobel-and-scharr.html 42 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/comparehist.py: -------------------------------------------------------------------------------- 1 | ''' file name : comparehist.py 2 | 3 | Description : This sample shows how to determine how well two histograms match each other. 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/histograms/histogram_comparison/histogram_comparison.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use cv2.compareHist and create 2D histograms 10 | 11 | Usage : python comparehist.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | base = cv2.imread('base.png') 19 | test1 = cv2.imread('test1.jpg') 20 | test2 = cv2.imread('test2.jpg') 21 | 22 | rows,cols = base.shape[:2] 23 | 24 | basehsv = cv2.cvtColor(base,cv2.COLOR_BGR2HSV) 25 | test1hsv = cv2.cvtColor(test1,cv2.COLOR_BGR2HSV) 26 | test2hsv = cv2.cvtColor(test2,cv2.COLOR_BGR2HSV) 27 | 28 | halfhsv = basehsv[rows/2:rows-1,cols/2:cols-1].copy() # Take lower half of the base image for testing 29 | 30 | hbins = 180 31 | sbins = 255 32 | hrange = [0,180] 33 | srange = [0,256] 34 | ranges = hrange+srange # ranges = [0,180,0,256] 35 | 36 | 37 | histbase = cv2.calcHist(basehsv,[0,1],None,[180,256],ranges) 38 | cv2.normalize(histbase,histbase,0,255,cv2.NORM_MINMAX) 39 | 40 | histhalf = cv2.calcHist(halfhsv,[0,1],None,[180,256],ranges) 41 | cv2.normalize(histhalf,histhalf,0,255,cv2.NORM_MINMAX) 42 | 43 | histtest1 = cv2.calcHist(test1hsv,[0,1],None,[180,256],ranges) 44 | cv2.normalize(histtest1,histtest1,0,255,cv2.NORM_MINMAX) 45 | 46 | histtest2 = cv2.calcHist(test2hsv,[0,1],None,[180,256],ranges) 47 | cv2.normalize(histtest2,histtest2,0,255,cv2.NORM_MINMAX) 48 | 49 | for i in xrange(4): 50 | base_base = cv2.compareHist(histbase,histbase,i) 51 | base_half = cv2.compareHist(histbase,histhalf,i) 52 | base_test1 = cv2.compareHist(histbase,histtest1,i) 53 | base_test2 = cv2.compareHist(histbase,histtest2,i) 54 | print "Method: {0} -- base-base: {1} , base-half: {2} , base-test1: {3}, base_test2: {4}".format(i,base_base,base_half,base_test1,base_test2) 55 | 56 | 57 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/convexhull.py: -------------------------------------------------------------------------------- 1 | ''' file name : convexhull.py 2 | 3 | Description : This sample shows how to find the convex hull of contours 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/shapedescriptors/hull/hull.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use cv2.convexHull() 10 | 11 | Usage : python convexhull.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | def thresh_callback(thresh): 19 | edges = cv2.Canny(blur,thresh,thresh*2) 20 | drawing = np.zeros(img.shape,np.uint8) # Image to draw the contours 21 | contours,hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 22 | for cnt in contours: 23 | hull = cv2.convexHull(cnt) 24 | cv2.drawContours(drawing,[cnt],0,(0,255,0),2) # draw contours in green color 25 | cv2.drawContours(drawing,[hull],0,(0,0,255),2) # draw contours in red color 26 | cv2.imshow('output',drawing) 27 | cv2.imshow('input',img) 28 | 29 | img = cv2.imread('messi5.jpg') 30 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 31 | blur = cv2.GaussianBlur(gray,(5,5),0) 32 | 33 | cv2.namedWindow('input') 34 | 35 | thresh = 100 36 | max_thresh = 255 37 | 38 | cv2.createTrackbar('canny thresh:','input',thresh,max_thresh,thresh_callback) 39 | 40 | thresh_callback(0) 41 | 42 | if cv2.waitKey(0) == 27: 43 | cv2.destroyAllWindows() 44 | 45 | ### For more details & feature extraction on contours, visit : http://opencvpython.blogspot.com/2012/04/contour-features.html 46 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/equalizehist.py: -------------------------------------------------------------------------------- 1 | ''' file name : equalizehist.py 2 | 3 | Description : This sample shows how to equalize histogram 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/histograms/histogram_equalization/histogram_equalization.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use cv2.equalizeHist() 10 | 11 | Usage : python equalizehist.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | img = cv2.imread('messi5.jpg') 19 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 20 | 21 | equ = cv2.equalizeHist(gray) # Remember histogram equalization works only for grayscale images 22 | 23 | cv2.imshow('src',gray) 24 | cv2.imshow('equ',equ) 25 | cv2.waitKey(0) 26 | cv2.destroyAllWindows() 27 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/findcontours.py: -------------------------------------------------------------------------------- 1 | ''' file name : findcontours.py 2 | 3 | Description : This sample shows how to find and draw contours 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/shapedescriptors/find_contours/find_contours.html#find-contours 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use 1) cv2.findContours() and 2)cv2.drawContours() 10 | 11 | Usage : python findcontours.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | def thresh_callback(thresh): 19 | edges = cv2.Canny(blur,thresh,thresh*2) 20 | drawing = np.zeros(img.shape,np.uint8) # Image to draw the contours 21 | contours,hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 22 | for cnt in contours: 23 | color = np.random.randint(0,255,(3)).tolist() # Select a random color 24 | cv2.drawContours(drawing,[cnt],0,color,2) 25 | cv2.imshow('output',drawing) 26 | cv2.imshow('input',img) 27 | 28 | img = cv2.imread('jonty2.jpg') 29 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 30 | blur = cv2.GaussianBlur(gray,(5,5),0) 31 | 32 | cv2.namedWindow('input',cv2.WINDOW_AUTOSIZE) 33 | 34 | thresh = 100 35 | max_thresh = 255 36 | 37 | cv2.createTrackbar('canny thresh:','input',thresh,max_thresh,thresh_callback) 38 | 39 | thresh_callback(thresh) 40 | 41 | if cv2.waitKey(0) == 27: 42 | cv2.destroyAllWindows() 43 | 44 | ### For more details & feature extraction on contours, visit : http://opencvpython.blogspot.com/2012/04/contour-features.html 45 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/geometric_transform.py: -------------------------------------------------------------------------------- 1 | ''' file name : geometric_transform.py 2 | 3 | Description : This sample shows image transformation and rotation 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/warp_affine/warp_affine.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn 1) Affine transformation 2) Image Rotation 10 | 11 | Usage : python 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | img = cv2.imread('messi5.jpg') 19 | rows,cols = img.shape[:2] 20 | 21 | # Source points 22 | srcTri = np.array([(0,0),(cols-1,0),(0,rows-1)], np.float32) 23 | 24 | # Corresponding Destination Points. Remember, both sets are of float32 type 25 | dstTri = np.array([(cols*0.0,rows*0.33),(cols*0.85,rows*0.25), (cols*0.15,rows*0.7)],np.float32) 26 | 27 | # Affine Transformation 28 | warp_mat = cv2.getAffineTransform(srcTri,dstTri) # Generating affine transform matrix of size 2x3 29 | dst = cv2.warpAffine(img,warp_mat,(cols,rows)) # Now transform the image, notice dst_size=(cols,rows), not (rows,cols) 30 | 31 | # Image Rotation 32 | center = (cols/2,rows/2) # Center point about which image is transformed 33 | angle = -50.0 # Angle, remember negative angle denotes clockwise rotation 34 | scale = 0.6 # Isotropic scale factor. 35 | 36 | rot_mat = cv2.getRotationMatrix2D(center,angle,scale) # Rotation matrix generated 37 | dst_rot = cv2.warpAffine(dst,rot_mat,(cols,rows)) # Now transform the image wrt rotation matrix 38 | 39 | cv2.imshow('dst_rt',dst_rot) 40 | cv2.waitKey(0) 41 | cv2.destroyAllWindows() 42 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/histogram1d.py: -------------------------------------------------------------------------------- 1 | ''' file name : histogram1d.py 2 | 3 | Description : This sample shows how to draw histogram for RGB color images 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/histograms/histogram_calculation/histogram_calculation.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use 1)cv2.calcHist(), 2)cv2.normalize and 3)cv2.polylines() 10 | 11 | Usage : python histogram1d.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | img = cv2.imread('messi5.jpg') 19 | h = np.zeros((300,256,3)) # image to draw histogram 20 | 21 | bins = np.arange(256).reshape(256,1) # Number of bins, since 256 colors, we need 256 bins 22 | color = [ (255,0,0),(0,255,0),(0,0,255) ] 23 | 24 | for ch,col in enumerate(color): 25 | hist_item = cv2.calcHist([img],[ch],None,[256],[0,256]) # Calculates the histogram 26 | cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX) # Normalize the value to fall below 255, to fit in image 'h' 27 | hist=np.int32(np.around(hist_item)) 28 | pts = np.column_stack((bins,hist)) # stack bins and hist, ie [[0,h0],[1,h1]....,[255,h255]] 29 | cv2.polylines(h,[pts],False,col) 30 | 31 | h=np.flipud(h) # You will need to flip the image vertically 32 | 33 | cv2.imshow('colorhist',h) 34 | cv2.waitKey(0) 35 | cv2.destroyAllWindows() 36 | 37 | # Here, there is no need of splitting the image to color planes,since calcHist will do it itself. 38 | # For more details, visit : http://opencvpython.blogspot.com/2012/04/drawing-histogram-in-opencv-python.html 39 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/houghcircles.py: -------------------------------------------------------------------------------- 1 | ''' file name : houghcircles.py 2 | 3 | Description : This sample shows how to detect circles in image with Hough Transform 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/hough_circle/hough_circle.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to find circles in the image and draw them 10 | 11 | Usage : python houghcircles.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | import sys 18 | 19 | if len(sys.argv)>1: 20 | filename = sys.argv[1] 21 | else: 22 | filename = 'board.jpg' 23 | 24 | img = cv2.imread(filename,0) 25 | if img==None: 26 | print "cannot open ",filename 27 | 28 | else: 29 | img = cv2.medianBlur(img,5) 30 | cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) 31 | circles = cv2.HoughCircles(img,cv2.cv.CV_HOUGH_GRADIENT,1,10,param1=100,param2=30,minRadius=5,maxRadius=20) 32 | circles = np.uint16(np.around(circles)) 33 | for i in circles[0,:]: 34 | cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),1) # draw the outer circle 35 | cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3) # draw the center of the circle 36 | 37 | cv2.imshow('detected circles',cimg) 38 | cv2.waitKey(0) 39 | cv2.destroyAllWindows() 40 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/houghlines.py: -------------------------------------------------------------------------------- 1 | ''' file name : houghlines.py 2 | 3 | Description : This sample shows how to detect lines using Hough Transform 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to find lines in an image and draw them 10 | 11 | Usage : python houghlines.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | print " Hough Lines demo " 19 | print " Press h to draw lines using cv2.HoughLines()" 20 | print " Press p to draw lines using cv2.HoughLinesP()" 21 | print " All the parameter values selected at random, Change it the way you like" 22 | 23 | im = cv2.imread('building.jpg') 24 | gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) 25 | edges = cv2.Canny(gray,150,200,apertureSize = 3) 26 | 27 | cv2.imshow('houghlines',im) 28 | 29 | while(True): 30 | img = im.copy() 31 | k = cv2.waitKey(0) 32 | 33 | if k == ord('h'): # Press 'h' to enable cv2.HoughLines() 34 | lines = cv2.HoughLines(edges,1,np.pi/180,275) 35 | for rho,theta in lines[0]: 36 | a = np.cos(theta) 37 | b = np.sin(theta) 38 | x0 = a*rho 39 | y0 = b*rho 40 | x1 = int(x0 + 1000*(-b)) # Here i have used int() instead of rounding the decimal value, so 3.8 --> 3 41 | y1 = int(y0 + 1000*(a)) # But if you want to round the number, then use np.around() function, then 3.8 --> 4.0 42 | x2 = int(x0 - 1000*(-b)) # But we need integers, so use int() function after that, ie int(np.around(x)) 43 | y2 = int(y0 - 1000*(a)) 44 | cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2) 45 | cv2.imshow('houghlines',img) 46 | 47 | elif k == ord('p'): # Press 'p' to enable cv2.HoughLinesP() 48 | lines = cv2.HoughLinesP(edges,1,np.pi/180,150, minLineLength = 100, maxLineGap = 10) 49 | for x1,y1,x2,y2 in lines[0]: 50 | cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2) 51 | cv2.imshow('houghlines',img) 52 | 53 | elif k == 27: # Press 'ESC' to exit 54 | break 55 | 56 | cv2.destroyAllWindows() 57 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/laplacian.py: -------------------------------------------------------------------------------- 1 | ''' file name : laplacian.py 2 | 3 | Description : This sample shows how to find laplacian of an image 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/laplace_operator/laplace_operator.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to find laplacian of an image 10 | 11 | Usage : python laplacian.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | kernel_size = 3 19 | scale = 1 20 | delta = 0 21 | ddepth = cv2.CV_16S 22 | 23 | img = cv2.imread('messi5.jpg') 24 | img = cv2.GaussianBlur(img,(3,3),0) 25 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 26 | 27 | gray_lap = cv2.Laplacian(gray,ddepth,ksize = kernel_size,scale = scale,delta = delta) 28 | dst = cv2.convertScaleAbs(gray_lap) 29 | 30 | cv2.imshow('laplacian',dst) 31 | cv2.waitKey(0) 32 | cv2.destroyAllWindows() 33 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/linear_filter.py: -------------------------------------------------------------------------------- 1 | ''' file name : linear_filter.py 2 | 3 | Description : This sample shows how to create a linear filter and apply convolution 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/filter_2d/filter_2d.html#filter-2d 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to 1) create a kernel and 2) apply convolution 10 | 11 | Usage : python linear_filter.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | img = cv2.imread('home.jpg') 19 | 20 | anchor = (-1,-1) 21 | delta = 0 22 | ddepth = -1 23 | 24 | ind = 0 25 | 26 | while(True): 27 | 28 | cv2.imshow('image',img) 29 | k = cv2.waitKey(500) 30 | 31 | if k==27: 32 | break 33 | 34 | kernel_size = 3 + 2*( ind%5 ) # trying for kernel sizes [3,5,7,9,11] 35 | kernel = np.ones((kernel_size,kernel_size),np.float32)/(kernel_size*kernel_size) 36 | 37 | cv2.filter2D(img,ddepth,kernel,img,anchor,delta,cv2.BORDER_DEFAULT) 38 | 39 | ind = ind+1 40 | 41 | cv2.destroyAllWindows() 42 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/minarearect.py: -------------------------------------------------------------------------------- 1 | ''' file name : minarearect.py 2 | 3 | Description : This sample shows how to find minimum area rectangle and fit an ellipse to a contour 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/shapedescriptors/bounding_rotated_ellipses/bounding_rotated_ellipses.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use 1)cv2.minAreaRect() and 2) cv2.fitEllipse() 10 | 11 | Usage : python minarearect.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | def thresh_callback(thresh): 19 | global contours 20 | edges = cv2.Canny(blur,thresh,thresh*2) 21 | drawing = np.zeros(img.shape,np.uint8) # Image to draw the contours 22 | contours,hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 23 | for cnt in contours: 24 | rect = cv2.minAreaRect(cnt) # rect = ((center_x,center_y),(width,height),angle) 25 | points = cv2.cv.BoxPoints(rect) # Find four vertices of rectangle from above rect 26 | points = np.int0(np.around(points)) # Round the values and make it integers 27 | 28 | ellipse = cv2.fitEllipse(cnt) # ellipse = ((center),(width,height of bounding rect), angle) 29 | 30 | cv2.drawContours(drawing,[cnt],0,(0,255,0),2) # draw contours in green color 31 | cv2.ellipse(drawing,ellipse,(0,0,255),2) # draw ellipse in red color 32 | cv2.polylines(drawing,[points],True,(255,0,0),2)# draw rectangle in blue color 33 | 34 | cv2.imshow('output',drawing) 35 | cv2.imshow('input',img) 36 | 37 | img = cv2.imread('new.bmp') 38 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 39 | blur = cv2.GaussianBlur(gray,(5,5),0) 40 | 41 | cv2.namedWindow('input') 42 | 43 | thresh = 200 44 | max_thresh = 255 45 | 46 | cv2.createTrackbar('canny thresh:','input',thresh,max_thresh,thresh_callback) 47 | 48 | thresh_callback(200) 49 | 50 | if cv2.waitKey(0) == 27: 51 | cv2.destroyAllWindows() 52 | 53 | ### For more details & feature extraction on contours, visit : http://opencvpython.blogspot.com/2012/04/contour-features.html 54 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/moments.py: -------------------------------------------------------------------------------- 1 | ''' file name : moments.py 2 | 3 | Description : This sample shows how to find area and centroid of a contour 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/shapedescriptors/moments/moments.html#moments 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use 1) cv2.moments and 2) cv.contourArea 10 | 11 | Usage : python moments.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | def thresh_callback(thresh): 19 | edges = cv2.Canny(blur,thresh,thresh*2) 20 | drawing = np.zeros(img.shape,np.uint8) # Image to draw the contours 21 | contours,hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 22 | for cnt in contours: 23 | moments = cv2.moments(cnt) # Calculate moments 24 | if moments['m00']!=0: 25 | cx = int(moments['m10']/moments['m00']) # cx = M10/M00 26 | cy = int(moments['m01']/moments['m00']) # cy = M01/M00 27 | moment_area = moments['m00'] # Contour area from moment 28 | contour_area = cv2.contourArea(cnt) # Contour area using in_built function 29 | 30 | cv2.drawContours(drawing,[cnt],0,(0,255,0),1) # draw contours in green color 31 | cv2.circle(drawing,(cx,cy),5,(0,0,255),-1) # draw centroids in red color 32 | cv2.imshow('output',drawing) 33 | cv2.imshow('input',img) 34 | 35 | img = cv2.imread('messi5.jpg') 36 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 37 | blur = cv2.GaussianBlur(gray,(5,5),0) 38 | 39 | cv2.namedWindow('input') 40 | 41 | thresh = 200 42 | max_thresh = 255 43 | 44 | cv2.createTrackbar('canny thresh:','input',thresh,max_thresh,thresh_callback) 45 | 46 | thresh_callback(200) 47 | 48 | if cv2.waitKey(0) == 27: 49 | cv2.destroyAllWindows() 50 | 51 | ### For more details & feature extraction on contours, visit : http://opencvpython.blogspot.com/2012/04/contour-features.html 52 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/morphology_1.py: -------------------------------------------------------------------------------- 1 | ''' file name : morphology_1.py 2 | 3 | Description : This sample shows how to erode and dilate images 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html#morphology-1 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to 1) Erode, 2) Dilate and 3) Use trackbar 10 | 11 | Usage : python morphology_1.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | global img 19 | 20 | def erode(erosion_size): 21 | erosion_size = 2*erosion_size+1 22 | kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(erosion_size,erosion_size)) 23 | eroded = cv2.erode(img,kernel) 24 | cv2.imshow('erosion demo',eroded) 25 | 26 | def dilate(dilation_size): 27 | dilation_size = 2*dilation_size+1 28 | kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(dilation_size,dilation_size)) 29 | dilated = cv2.dilate(img,kernel) 30 | cv2.imshow('dilation demo',dilated) 31 | 32 | 33 | erosion_size = 0 # initial kernel size = 1 34 | dilation_size = 0 35 | 36 | max_kernel_size = 21 # maximum kernel size = 43 37 | 38 | img = cv2.imread('home.jpg') 39 | 40 | cv2.namedWindow('erosion demo',cv2.CV_WINDOW_AUTOSIZE) 41 | cv2.namedWindow('dilation demo',cv2.CV_WINDOW_AUTOSIZE) 42 | 43 | # Creating trackbar for kernel size 44 | cv2.createTrackbar('Size: 2n+1','erosion demo',erosion_size,max_kernel_size,erode) 45 | cv2.createTrackbar('Size: 2n+1','dilation demo',dilation_size,max_kernel_size,dilate) 46 | 47 | erode(0) 48 | dilate(0) 49 | if cv2.waitKey(0) == 27: 50 | cv2.destroyAllWindows() 51 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/pointpolygontest.py: -------------------------------------------------------------------------------- 1 | ''' file name : pointpolygontest.py 2 | 3 | Description : This sample shows how to find distance from a point to a contour 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/shapedescriptors/point_polygon_test/point_polygon_test.html 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use cv2.pointPolygonTest() 10 | 11 | Usage : python pointpolygontest.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | r = 100 19 | 20 | src = np.zeros((4*r,4*r),np.uint8) 21 | rows,cols = src.shape 22 | 23 | # draw an polygon on image src 24 | points = [ [1.5*r,1.34*r], [r,2*r], [1.5*r,2.866*r], [2.5*r,2.866*r],[3*r,2*r],[2.5*r,1.34*r] ] 25 | points = np.array(points,np.int0) 26 | cv2.polylines(src,[points],True,255,3) 27 | 28 | contours,hierarchy = cv2.findContours(src,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 29 | 30 | res = np.zeros(src.shape,np.float32) # array to store distances 31 | drawing = np.zeros((rows,cols,3),np.uint8) # image to draw the distance 32 | cnt = contours[0] # We take only one contour for testing 33 | 34 | # Calculate distance from each point 35 | for i in xrange(rows): 36 | for j in xrange(cols): 37 | res.itemset((i,j),cv2.pointPolygonTest(cnt,(j,i),True)) 38 | 39 | 40 | mini,maxi = np.abs(cv2.minMaxLoc(res)[:2]) # Find minimum and maximum to adjust colors 41 | mini = 255.0/mini 42 | maxi = 255.0/maxi 43 | 44 | for i in xrange(rows): # Now we colorise as per distance 45 | for j in xrange(cols): 46 | if res.item((i,j))<0: 47 | drawing.itemset((i,j,0),255-int(abs(res.item(i,j))*mini)) # If outside, blue color 48 | elif res.item((i,j))>0: 49 | drawing.itemset((i,j,2),255-int(res.item(i,j)*maxi)) # If inside, red color 50 | else: 51 | drawing[i,j]=[255,255,255] # If on the contour, white color. 52 | 53 | cv2.imshow('point',drawing) 54 | cv2.waitKey(0) 55 | cv2.destroyAllWindows() 56 | 57 | ### For more details & feature extraction on contours, visit : http://opencvpython.blogspot.com/2012/04/contour-features.html 58 | ### For much more better and faster (50X) method, visit:http://opencvpython.blogspot.com/2012/06/fast-array-manipulation-in-numpy.html 59 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/pyramids.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | img = cv2.imread('home.jpg') 5 | 6 | ''' file name : pyramids.py 7 | 8 | Description : This sample shows how to downsample and upsample images 9 | 10 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/pyramids/pyramids.html#pyramids 11 | 12 | Level : Beginner 13 | 14 | Benefits : Learn to use 1) cv2.pyrUp and 2) cv2.pyrDown 15 | 16 | Usage : python pyramids.py 17 | 18 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 19 | 20 | 21 | print " Zoom In-Out demo " 22 | print " Press u to zoom " 23 | print " Press d to zoom " 24 | 25 | img = cv2.imread('home.jpg') 26 | 27 | while(1): 28 | h,w = img.shape[:2] 29 | 30 | cv2.imshow('image',img) 31 | k = cv2.waitKey(10) 32 | 33 | if k==27 : 34 | break 35 | 36 | elif k == ord('u'): # Zoom in, make image double size 37 | img = cv2.pyrUp(img,dstsize = (2*w,2*h)) 38 | 39 | elif k == ord('d'): # Zoom down, make image half the size 40 | img = cv2.pyrDown(img,dstsize = (w/2,h/2)) 41 | 42 | cv2.destroyAllWindows() 43 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/remap.py: -------------------------------------------------------------------------------- 1 | ''' file name : remap.py 2 | 3 | Description : This sample shows how to remap images 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/remap/remap.html#remap 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use remap function 10 | 11 | Usage : python remap.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | def update(): 19 | global ind 20 | ind = ind%4 21 | for j in xrange(rows): 22 | for i in xrange(cols): 23 | if ind == 0: # Resize and center the image 24 | if 0.25*cols< i <0.75*cols and 0.25*rows< j <0.75*rows: 25 | map_x.itemset((j,i),2*( i - cols*0.25 ) + 0.5) 26 | map_y.itemset((j,i),2*( j - rows*0.25 ) + 0.5) 27 | else: # Other pixel values set to zero 28 | map_x.itemset((j,i),0) 29 | map_y.itemset((j,i),0) 30 | 31 | elif ind == 1: # Flip image in vertical direction, alternatively you can use np.flipud or cv2.flip 32 | map_x.itemset((j,i),i) 33 | map_y.itemset((j,i),rows-j) 34 | 35 | elif ind == 2: # Flip image in horizontal direction, you can use np.fliplr or cv2.flip 36 | map_x.itemset((j,i),cols-i) 37 | map_y.itemset((j,i),j) 38 | 39 | elif ind == 3: # Flip image in both the directions, you can use cv2.flip(flag = -1) 40 | map_x.itemset((j,i),cols-i) 41 | map_y.itemset((j,i),rows-j) 42 | ind = ind+1 43 | 44 | img = cv2.imread('messi5.jpg') 45 | ind = 0 46 | map_x = np.zeros(img.shape[:2],np.float32) 47 | map_y = np.zeros(img.shape[:2],np.float32) 48 | rows,cols = img.shape[:2] 49 | while(True): 50 | update() 51 | dst = cv2.remap(img,map_x,map_y,cv2.INTER_LINEAR) 52 | cv2.imshow('dst',dst) 53 | if cv2.waitKey(1000)==27: 54 | break 55 | cv2.destroyAllWindows() 56 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/smoothing.py: -------------------------------------------------------------------------------- 1 | ''' file name : smoothing.py 2 | 3 | Description : This sample shows how to smooth image using various filters 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/gausian_median_blur_bilateral_filter/gausian_median_blur_bilateral_filter.html#smoothing 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use 1) Blur, 2) GaussianBlur, 3) MedianBlur, 4) BilateralFilter and differences between them 10 | 11 | Usage : python smoothing.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | DELAY_CAPTION = 1500; 19 | DELAY_BLUR = 500; 20 | 21 | img = cv2.imread('lena.jpg') 22 | 23 | for i in xrange(1,31,2): 24 | blur = cv2.blur(img,(i,i)) 25 | string = 'blur : kernel size - '+str(i) 26 | cv2.putText(blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 27 | cv2.imshow('Blur',blur) 28 | cv2.waitKey(DELAY_BLUR) 29 | 30 | for i in xrange(1,31,2): 31 | gaussian_blur = cv2.GaussianBlur(img,(i,i),0) 32 | string = 'guassian_blur : kernel size - '+str(i) 33 | cv2.putText(gaussian_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 34 | cv2.imshow('Blur',gaussian_blur) 35 | cv2.waitKey(DELAY_BLUR) 36 | 37 | cv2.waitKey(DELAY_CAPTION) 38 | 39 | for i in xrange(1,31,2): 40 | median_blur = cv2.medianBlur(img,i) 41 | string = 'median_blur : kernel size - '+str(i) 42 | cv2.putText(median_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 43 | cv2.imshow('Blur',median_blur) 44 | cv2.waitKey(DELAY_BLUR) 45 | 46 | cv2.waitKey(DELAY_CAPTION) 47 | 48 | for i in xrange(1,31,2): # Remember, bilateral is a bit slow, so as value go higher, it takes long time 49 | bilateral_blur = cv2.bilateralFilter(img,i, i*2,i/2) 50 | string = 'bilateral_blur : kernel size - '+str(i) 51 | cv2.putText(bilateral_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 52 | cv2.imshow('Blur',bilateral_blur) 53 | cv2.waitKey(DELAY_BLUR) 54 | 55 | cv2.waitKey(DELAY_CAPTION) 56 | cv2.destroyAllWindows() 57 | 58 | ## For more info about this , visit: http://opencvpython.blogspot.com/2012/06/smoothing-techniques-in-opencv.html 59 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/sobel.py: -------------------------------------------------------------------------------- 1 | ''' file name : sobel.py 2 | 3 | Description : This sample shows how to find derivatives of an image 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/sobel_derivatives/sobel_derivatives.html#sobel-derivatives 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use Sobel and Scharr derivatives 10 | 11 | Usage : python sobel.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | scale = 1 19 | delta = 0 20 | ddepth = cv2.CV_16S 21 | 22 | img = cv2.imread('messi5.jpg') 23 | img = cv2.GaussianBlur(img,(3,3),0) 24 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 25 | 26 | # Gradient-X 27 | grad_x = cv2.Sobel(gray,ddepth,1,0,ksize = 3, scale = scale, delta = delta,borderType = cv2.BORDER_DEFAULT) 28 | #grad_x = cv2.Scharr(gray,ddepth,1,0) 29 | 30 | # Gradient-Y 31 | grad_y = cv2.Sobel(gray,ddepth,0,1,ksize = 3, scale = scale, delta = delta, borderType = cv2.BORDER_DEFAULT) 32 | #grad_y = cv2.Scharr(gray,ddepth,0,1) 33 | 34 | abs_grad_x = cv2.convertScaleAbs(grad_x) # converting back to uint8 35 | abs_grad_y = cv2.convertScaleAbs(grad_y) 36 | 37 | dst = cv2.addWeighted(abs_grad_x,0.5,abs_grad_y,0.5,0) 38 | #dst = cv2.add(abs_grad_x,abs_grad_y) 39 | 40 | cv2.imshow('dst',dst) 41 | cv2.waitKey(0) 42 | cv2.destroyAllWindows() 43 | 44 | # To see the results, visit : http://opencvpython.blogspot.com/2012/06/image-derivatives-sobel-and-scharr.html 45 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/3_imgproc/templatematching.py: -------------------------------------------------------------------------------- 1 | ''' file name : templatematching.py 2 | 3 | Description : This sample shows how to find location of a template image in original image 4 | 5 | This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/histograms/template_matching/template_matching.html#template-matching 6 | 7 | Level : Beginner 8 | 9 | Benefits : Learn to use 1) cv2.matchTemplate and 2) cv2.minMaxLoc() 10 | 11 | Usage : python templatematching.py 12 | 13 | Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' 14 | 15 | import cv2 16 | import numpy as np 17 | 18 | def match(matchvalue): 19 | img2 = img.copy() 20 | 21 | result = cv2.matchTemplate(img,template,matchvalue) 22 | 23 | cv2.normalize(result,result,0,255,cv2.NORM_MINMAX) 24 | 25 | mini,maxi,(mx,my),(Mx,My) = cv2.minMaxLoc(result) # We find minimum and maximum value locations in result 26 | 27 | if matchvalue in [0,1]: # For SQDIFF and SQDIFF_NORMED, the best matches are lower values. 28 | MPx,MPy = mx,my 29 | else: # Other cases, best matches are higher values. 30 | MPx,MPy = Mx,My 31 | 32 | # Normed methods give better results, ie matchvalue = [1,3,5], others sometimes shows errors 33 | cv2.rectangle(img2, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2) 34 | 35 | cv2.imshow('input',img2) 36 | cv2.imshow('output',result) 37 | 38 | img = cv2.imread('messi4.jpg') 39 | template = cv2.imread('template.jpg') 40 | 41 | trows,tcols = template.shape[:2] # template rows and cols 42 | 43 | cv2.namedWindow('input') 44 | 45 | matchvalue = 0 46 | max_Trackbar = 5 47 | 48 | cv2.createTrackbar('method','input',matchvalue,max_Trackbar,match) 49 | 50 | match(0) 51 | 52 | if cv2.waitKey(0) == 27: 53 | cv2.destroyAllWindows() 54 | -------------------------------------------------------------------------------- /Official_Tutorial_Python_Codes/README: -------------------------------------------------------------------------------- 1 | This folder contains Python codes for C++ codes in OpenCV official tutorials : 'http://opencv.itseez.com/doc/tutorials/tutorials.html' 2 | 3 | Details : 4 | 5 | Introduction to OpenCV 6 | 1) Load and Display an Image --- display_image.py 7 | 2) Load, Modify, and Save an Image --- modify_image.py 8 | 9 | Core Module 10 | 1) Mask operations on matrices --- fiter2d.py 11 | 2) Adding (blending) two images using OpenCV --- add_images.py 12 | 3) Changing the contrast and brightness of an image! --- BasicLinearTransforms.py 13 | 14 | Imgproc module 15 | -------------------------------------------------------------------------------- /OpenCV_Python_Blog/kmeans_clustering/kmeans_data.txt: -------------------------------------------------------------------------------- 1 | K-MEANS CLUSTERING WITH SCIPY - DATA 2 | 3 | ***************************************************************************** 4 | K-Means with one feature 5 | ***************************************************************************** 6 | >>> z # z is test data array of size 50x1 7 | array([ 47, 71, 62, 43, 98, 47, 78, 47, 53, 38, 93, 97, 98, 8 | 86, 47, 36, 54, 36, 59, 32, 57, 47, 30, 53, 94, 175, 9 | 215, 184, 233, 219, 199, 198, 235, 235, 221, 219, 241, 215, 250, 10 | 176, 175, 198, 189, 180, 184, 216, 192, 220, 203, 209]) 11 | 12 | >>> centers # it is the centroids array of size 2x1 13 | array([[207],[ 60]]) # obtained after kmeans clustering 14 | 15 | >>> code # it is the labelled data 16 | array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 17 | 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18 | 0, 0, 0, 0]) 19 | 20 | >>> distance # distance between z and corresponding center 21 | array([ 13., 11., 2., 17., 38., 13., 18., 13., 7., 22., 33., 22 | 37., 38., 26., 13., 24., 6., 24., 1., 28., 3., 13., 23 | 30., 7., 34., 32., 8., 23., 26., 12., 8., 9., 28., 24 | 28., 14., 12., 34., 8., 43., 31., 32., 9., 18., 27., 25 | 23., 9., 15., 13., 4., 2.]) 26 | 27 | >>> a # data with centroid = 207, it is a column vector 28 | array([175, 215, 184, 233, 219, 199, 198, 235, 235, 221, 219, 241, 215, 29 | 250, 176, 175, 198, 189, 180, 184, 216, 192, 220, 203, 209]) 30 | 31 | >>> b # data with centroid = 60, it is a column vector 32 | array([47, 71, 62, 43, 98, 47, 78, 47, 53, 38, 93, 97, 98, 86, 47, 36, 54, 33 | 36, 59, 32, 57, 47, 30, 53, 94]) 34 | 35 | ****************************************************************************** 36 | K-Means with more than one feature 37 | ****************************************************************************** 38 | 39 | >>> z 40 | array([[33, 36], 41 | [30, 46], 42 | [32, 27], 43 | [27, 25], 44 | [37, 39], 45 | [47, 34], 46 | [36, 38], 47 | [42, 32], 48 | [37, 39], 49 | [31, 37], 50 | [33, 49], 51 | [31, 43], 52 | [42, 43], 53 | [38, 33], 54 | [35, 29], 55 | [46, 37], 56 | [36, 49], 57 | [45, 26], 58 | [36, 43], 59 | [48, 34], 60 | [47, 29], 61 | [35, 38], 62 | [44, 32], 63 | [31, 33], 64 | [43, 47], 65 | [83, 64], 66 | [67, 66], 67 | [73, 65], 68 | [68, 68], 69 | [74, 80], 70 | [70, 71], 71 | [61, 81], 72 | [78, 67], 73 | [78, 84], 74 | [72, 72], 75 | [78, 80], 76 | [80, 82], 77 | [62, 67], 78 | [83, 67], 79 | [68, 68], 80 | [83, 72], 81 | [70, 62], 82 | [75, 81], 83 | [69, 79], 84 | [71, 64], 85 | [80, 79], 86 | [62, 60], 87 | [72, 63], 88 | [76, 77], 89 | [68, 81]]) 90 | 91 | >>> center 92 | array([[72, 72], 93 | [37, 36]]) 94 | 95 | >>> code 96 | array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 97 | 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 98 | 0, 0, 0, 0]) -------------------------------------------------------------------------------- /OpenCV_Python_Blog/sudoku_v_0.0.6/.picasa.ini: -------------------------------------------------------------------------------- 1 | [sudoku.jpg] 2 | faces=rect64(268900003ba41319),ffffffffffffffff 3 | backuphash=16393 4 | -------------------------------------------------------------------------------- /OpenCV_Python_Blog/sudoku_v_0.0.6/README.txt: -------------------------------------------------------------------------------- 1 | Hi, 2 | 3 | This is the code for visual sudoku solver. It is still under development although it works fine for the given image in the folder. 4 | 5 | I haven't tested it for other images. 6 | 7 | Run the "sudoku.py" file in this folder. If you want to try for other images, change code accordingly. 8 | 9 | Explanations for first few portions of code can be found in my blog : www.opencvpython.blogspot.com 10 | 11 | Regards, 12 | 13 | Abid Rahman K. -------------------------------------------------------------------------------- /OpenCV_Python_Blog/sudoku_v_0.0.6/perfect.py: -------------------------------------------------------------------------------- 1 | ''' This module solves a sudoku, This is actually written by Peter Norvig 2 | Code and Explanation can be found here : norvig.com/sudoku.html''' 3 | 4 | def cross(A, B): 5 | "Cross product of elements in A and elements in B." 6 | return [a+b for a in A for b in B] 7 | 8 | digits = '123456789' 9 | rows = 'ABCDEFGHI' 10 | cols = digits 11 | squares = cross(rows, cols) 12 | unitlist = ([cross(rows, c) for c in cols] + 13 | [cross(r, cols) for r in rows] + 14 | [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]) 15 | units = dict((s, [u for u in unitlist if s in u]) for s in squares) 16 | #print(units) 17 | peers = dict((s, set(sum(units[s],[]))-set([s])) for s in squares) 18 | 19 | def parse_grid(grid): 20 | """Convert grid to a dict of possible values, {square: digits}, or 21 | return False if a contradiction is detected.""" 22 | ## To start, every square can be any digit; then assign values from the grid. 23 | values = dict((s, digits) for s in squares) 24 | for s,d in grid_values(grid).items(): 25 | if d in digits and not assign(values, s, d): 26 | return False ## (Fail if we can't assign d to square s.) 27 | return values 28 | 29 | def grid_values(grid): 30 | "Convert grid into a dict of {square: char} with '0' or '.' for empties." 31 | chars = [c for c in grid if c in digits or c in '0.'] 32 | assert len(chars) == 81 33 | return dict(zip(squares, chars)) 34 | 35 | def assign(values, s, d): 36 | """Eliminate all the other values (except d) from values[s] and propagate. 37 | Return values, except return False if a contradiction is detected.""" 38 | other_values = values[s].replace(d, '') 39 | if all(eliminate(values, s, d2) for d2 in other_values): 40 | return values 41 | else: 42 | return False 43 | 44 | def eliminate(values, s, d): 45 | """Eliminate d from values[s]; propagate when values or places <= 2. 46 | Return values, except return False if a contradiction is detected.""" 47 | if d not in values[s]: 48 | return values ## Already eliminated 49 | values[s] = values[s].replace(d,'') 50 | ## (1) If a square s is reduced to one value d2, then eliminate d2 from the peers. 51 | if len(values[s]) == 0: 52 | return False ## Contradiction: removed last value 53 | elif len(values[s]) == 1: 54 | d2 = values[s] 55 | if not all(eliminate(values, s2, d2) for s2 in peers[s]): 56 | return False 57 | ## (2) If a unit u is reduced to only one place for a value d, then put it there. 58 | for u in units[s]: 59 | dplaces = [s for s in u if d in values[s]] 60 | if len(dplaces) == 0: 61 | return False ## Contradiction: no place for this value 62 | elif len(dplaces) == 1: 63 | # d can only be in one place in unit; assign it there 64 | if not assign(values, dplaces[0], d): 65 | return False 66 | return values 67 | 68 | def display(values): 69 | "Display these values as a 2-D grid." 70 | width = 1+max(len(values[s]) for s in squares) 71 | line = '+'.join(['-'*(width*3)]*3) 72 | for r in rows: 73 | print (''.join(values[r+c].center(width)+('|' if c in '36' else '') for c in cols)) 74 | if r in 'CF': print(line) 75 | print 76 | 77 | def solve(grid): return search(parse_grid(grid)) 78 | 79 | def search(values): 80 | "Using depth-first search and propagation, try all possible values." 81 | if values is False: 82 | return False ## Failed earlier 83 | if all(len(values[s]) == 1 for s in squares): 84 | return values ## Solved! 85 | ## Chose the unfilled square s with the fewest possibilities 86 | n,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1) 87 | return some(search(assign(values.copy(), s, d)) 88 | for d in values[s]) 89 | 90 | def some(seq): 91 | "Return some element of seq that is true." 92 | for e in seq: 93 | if e: return e 94 | return False 95 | 96 | import time, random 97 | 98 | def solve_all(grids, name='', showif=0.0): 99 | """Attempt to solve a sequence of grids. Report results. 100 | When showif is a number of seconds, display puzzles that take longer. 101 | When showif is None, don't display any puzzles.""" 102 | def time_solve(grid): 103 | start = time.clock() 104 | values = solve(grid) 105 | t = time.clock()-start 106 | ## Display puzzles that take long enough 107 | if showif is not None and t > showif: 108 | display(grid_values(grid)) 109 | if values: display(values) 110 | print ('(%.2f seconds)\n' % t) 111 | return (t, solved(values)) 112 | times, results = zip(*[time_solve(grid) for grid in grids]) 113 | N = len(grids) 114 | if N > 1: 115 | print ("Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max %.2f secs)." % (sum(results), N, name, sum(times)/N, N/sum(times), max(times))) 116 | 117 | def solved(values): 118 | "A puzzle is solved if each unit is a permutation of the digits 1 to 9." 119 | def unitsolved(unit): return set(values[s] for s in unit) == set(digits) 120 | return values is not False and all(unitsolved(unit) for unit in unitlist) 121 | 122 | def from_file(filename, sep='\n'): 123 | "Parse a file into a list of strings, separated by sep." 124 | # return file(filename).read().strip().split(sep) 125 | pass 126 | 127 | def random_puzzle(N=17): 128 | """Make a random puzzle by making N assignments. Restart on contradictions. 129 | Note the resulting puzzle is not guaranteed to be solvable, but empirically 130 | about 99.8% of them are solvable.""" 131 | values = dict((s, digits) for s in squares) 132 | for s in random.sample(squares, N): 133 | if not assign(values, s, random.choice(values[s])): 134 | return random_puzzle(N) ## Give up and make a new puzzle 135 | return ''.join(values[s] if len(values[s])==1 else '.' for s in squares) 136 | 137 | def shuffled(seq): 138 | "Return a randomly shuffled copy of the input sequence." 139 | seq = list(seq) 140 | random.shuffle(seq) 141 | return seq 142 | 143 | grid1 = '003020600900305001001806400008102900700000008006708200002609500800203009005010300' 144 | grid2 = '4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......' 145 | hard1 = '.....6....59.....82....8....45........3........6..3.54...325..6..................' 146 | grid3 = '79......3.......6.8.1..4..2..5......3..1......4...62.92...3...6.3.6.5421.........' 147 | extreme ='.26....1.75......2..86.1.9......3....9.4.8.2....1......1.5.92..6......57.3....98.' 148 | #result = solved(grid_values(extreme)) 149 | def solve_sudoku(s): 150 | k=solve(s) 151 | 152 | keys = k.keys() 153 | keys.sort() 154 | ans = ''.join(k[i] for i in keys) 155 | return ans 156 | 157 | -------------------------------------------------------------------------------- /OpenCV_Python_Blog/sudoku_v_0.0.6/sampleout.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abidrahmank/OpenCV2-Python/0889000b20a1e02ef9a64b0213dfe3136311890a/OpenCV_Python_Blog/sudoku_v_0.0.6/sampleout.jpg -------------------------------------------------------------------------------- /OpenCV_Python_Blog/sudoku_v_0.0.6/samples_pixels.data: -------------------------------------------------------------------------------- 1 | 2.000000000000000000e+00 2 | 1.000000000000000000e+00 3 | 3.000000000000000000e+00 4 | 2.000000000000000000e+00 5 | 8.000000000000000000e+00 6 | 2.000000000000000000e+00 7 | 3.000000000000000000e+00 8 | 5.000000000000000000e+00 9 | 7.000000000000000000e+00 10 | 5.000000000000000000e+00 11 | 9.000000000000000000e+00 12 | 3.000000000000000000e+00 13 | 1.000000000000000000e+00 14 | 2.000000000000000000e+00 15 | 3.000000000000000000e+00 16 | 4.000000000000000000e+00 17 | 8.000000000000000000e+00 18 | 7.000000000000000000e+00 19 | 5.000000000000000000e+00 20 | 4.000000000000000000e+00 21 | 6.000000000000000000e+00 22 | 6.000000000000000000e+00 23 | 7.000000000000000000e+00 24 | 8.000000000000000000e+00 25 | 9.000000000000000000e+00 26 | 7.000000000000000000e+00 27 | 1.000000000000000000e+00 28 | 4.000000000000000000e+00 29 | 7.000000000000000000e+00 30 | 9.000000000000000000e+00 31 | 6.000000000000000000e+00 32 | 9.000000000000000000e+00 33 | 3.000000000000000000e+00 34 | 5.000000000000000000e+00 35 | 7.000000000000000000e+00 36 | 8.000000000000000000e+00 37 | 2.000000000000000000e+00 38 | 6.000000000000000000e+00 39 | 9.000000000000000000e+00 40 | 6.000000000000000000e+00 41 | 4.000000000000000000e+00 42 | 3.000000000000000000e+00 43 | 5.000000000000000000e+00 44 | 2.000000000000000000e+00 45 | 2.000000000000000000e+00 46 | 4.000000000000000000e+00 47 | 9.000000000000000000e+00 48 | 1.000000000000000000e+00 49 | 9.000000000000000000e+00 50 | 6.000000000000000000e+00 51 | 7.000000000000000000e+00 52 | 4.000000000000000000e+00 53 | 5.000000000000000000e+00 54 | 1.000000000000000000e+00 55 | 2.000000000000000000e+00 56 | 3.000000000000000000e+00 57 | 1.000000000000000000e+00 58 | 2.000000000000000000e+00 59 | 8.000000000000000000e+00 60 | 2.000000000000000000e+00 61 | 3.000000000000000000e+00 62 | 5.000000000000000000e+00 63 | 7.000000000000000000e+00 64 | 5.000000000000000000e+00 65 | 9.000000000000000000e+00 66 | 3.000000000000000000e+00 67 | 1.000000000000000000e+00 68 | 2.000000000000000000e+00 69 | 3.000000000000000000e+00 70 | 4.000000000000000000e+00 71 | 8.000000000000000000e+00 72 | 7.000000000000000000e+00 73 | 5.000000000000000000e+00 74 | 4.000000000000000000e+00 75 | 6.000000000000000000e+00 76 | 6.000000000000000000e+00 77 | 7.000000000000000000e+00 78 | 8.000000000000000000e+00 79 | 9.000000000000000000e+00 80 | 7.000000000000000000e+00 81 | -------------------------------------------------------------------------------- /OpenCV_Python_Blog/sudoku_v_0.0.6/sudoku.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abidrahmank/OpenCV2-Python/0889000b20a1e02ef9a64b0213dfe3136311890a/OpenCV_Python_Blog/sudoku_v_0.0.6/sudoku.jpg -------------------------------------------------------------------------------- /OpenCV_Python_Blog/sudoku_v_0.0.6/sudoku.py: -------------------------------------------------------------------------------- 1 | ''' This script takes a sudoku image as input, solves it and puts answer on image itself. 2 | 3 | Usage : python sudoku.py ''' 4 | 5 | import cv2 6 | import numpy as np 7 | import time,sys 8 | from perfect import solve_sudoku 9 | 10 | ############## Load OCR data for training ####################################### 11 | samples = np.float32(np.loadtxt('feature_vector_pixels.data')) 12 | responses = np.float32(np.loadtxt('samples_pixels.data')) 13 | 14 | model = cv2.KNearest() 15 | model.train(samples, responses) 16 | 17 | ############# Function to put vertices in clockwise order ###################### 18 | def rectify(h): 19 | ''' this function put vertices of square we got, in clockwise order ''' 20 | h = h.reshape((4,2)) 21 | hnew = np.zeros((4,2),dtype = np.float32) 22 | 23 | add = h.sum(1) 24 | hnew[0] = h[np.argmin(add)] 25 | hnew[2] = h[np.argmax(add)] 26 | 27 | diff = np.diff(h,axis = 1) 28 | hnew[1] = h[np.argmin(diff)] 29 | hnew[3] = h[np.argmax(diff)] 30 | 31 | return hnew 32 | 33 | ################ Now starts main program ########################### 34 | 35 | img = cv2.imread('sudoku.jpg') 36 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 37 | 38 | thresh = cv2.adaptiveThreshold(gray,255,1,1,5,2) 39 | contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 40 | 41 | image_area = gray.size # this is area of the image 42 | 43 | for i in contours: 44 | if cv2.contourArea(i)> image_area/2: # if area of box > half of image area, it is possibly the biggest blob 45 | peri = cv2.arcLength(i,True) 46 | approx = cv2.approxPolyDP(i,0.02*peri,True) 47 | #cv2.drawContours(img,[approx],0,(0,255,0),2,cv2.CV_AA) 48 | break 49 | 50 | ################# Now we got sudoku boundaries, Transform it to perfect square ###################### 51 | 52 | h = np.array([ [0,0],[449,0],[449,449],[0,449] ],np.float32) # this is corners of new square image taken in CW order 53 | 54 | approx=rectify(approx) # we put the corners of biggest square in CW order to match with h 55 | 56 | retval = cv2.getPerspectiveTransform(approx,h) # apply perspective transformation 57 | warp = cv2.warpPerspective(img,retval,(450,450)) # Now we get perfect square with size 450x450 58 | 59 | warpg = cv2.cvtColor(warp,cv2.COLOR_BGR2GRAY) # kept a gray-scale copy of warp for further use 60 | 61 | ############ now take each element for inspection ############## 62 | 63 | sudo = np.zeros((9,9),np.uint8) # a 9x9 matrix to store our sudoku puzzle 64 | 65 | smooth = cv2.GaussianBlur(warpg,(3,3),3) 66 | thresh = cv2.adaptiveThreshold(smooth,255,0,1,5,2) 67 | kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3)) 68 | erode = cv2.erode(thresh,kernel,iterations =1) 69 | dilate =cv2.dilate(erode,kernel,iterations =1) 70 | contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 71 | 72 | for cnt in contours: 73 | area = cv2.contourArea(cnt) 74 | if 100