├── README ├── README.md ├── convertGray.py ├── demhist.py ├── diplay_image.py ├── display_image.py ├── fast2.py ├── filters_cont.py ├── floodFill.py ├── installation.txt ├── tutorial7_filters.py ├── tutorial_10.py ├── tutorial_11.py ├── tutorial_12.py ├── tutorial_12b.py ├── tutorial_12c.py ├── tutorial_13.py ├── tutorial_14.py ├── tutorial_14Harris.py ├── tutorial_8 ├── tutorial_8.py ├── tutorial_9.py └── yellow_rose.py /README: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cesco345/opencv/da8dc7236594ce2fc5e1cb27c2959b1e55808a24/README -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | opencv 2 | ====== 3 | 4 | 5 | OpenCV was designed for computational efficiency and with a strong focus on real-time applications. Written in optimized C/C++, the library can take advantage of multi-core processing. Adopted all around the world, OpenCV has more than 47 thousand people in their user community and estimated number of downloads exceeding 6 million. Usage ranges from interactive art, to mines inspection, stitching maps on the web or through advanced robotics. 6 | -------------------------------------------------------------------------------- /convertGray.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from numpy import * 3 | from pylab import * 4 | 5 | import cv2 6 | 7 | # windows to display image 8 | cv2.namedWindow("Color Image") 9 | 10 | 11 | # read the image 12 | im = cv2.imread('/home/cesco/Desktop/images/e­instein_color.jpg') 13 | 14 | # create a grayscale version 15 | gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) 16 | 17 | # save the image 18 | cv2.imwrite('/home/cesco/Desktop/images/­gray_result.png', gray) 19 | 20 | # show image 21 | cv2.imshow("Color Image", im ) 22 | 23 | # exit at closing of window 24 | cv2.waitKey(0) 25 | cv2.destroyAllWindows() 26 | -------------------------------------------------------------------------------- /demhist.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import cv2.cv as cv 3 | import sys 4 | import urllib2 5 | 6 | hist_size = 64 7 | range_0 = [0, 256] 8 | ranges = [ range_0 ] 9 | 10 | class DemHist: 11 | 12 | def __init__(self, src_image): 13 | self.src_image = src_image 14 | self.dst_image = cv.CloneMat(src_image) 15 | self.hist_image = cv.CreateImage((320, 200), 8, 1) 16 | self.hist = cv.CreateHist([hist_size], cv.CV_HIST_ARRAY, ranges, 1) 17 | 18 | self.brightness = 0 19 | self.contrast = 0 20 | 21 | cv.NamedWindow("image", 0) 22 | cv.NamedWindow("histogram", 0) 23 | cv.CreateTrackbar("brightness", "image", 100, 200, self.update_brightness) 24 | cv.CreateTrackbar("contrast", "image", 100, 200, self.update_contrast) 25 | 26 | self.update_brightcont() 27 | 28 | def update_brightness(self, val): 29 | self.brightness = val - 100 30 | self.update_brightcont() 31 | 32 | def update_contrast(self, val): 33 | self.contrast = val - 100 34 | self.update_brightcont() 35 | 36 | def update_brightcont(self): 37 | # The algorithm is by Werner D. Streidt 38 | # (http://visca.com/ffactory/archives/5-99/msg00021.html) 39 | 40 | if self.contrast > 0: 41 | delta = 127. * self.contrast / 100 42 | a = 255. / (255. - delta * 2) 43 | b = a * (self.brightness - delta) 44 | else: 45 | delta = -128. * self.contrast / 100 46 | a = (256. - delta * 2) / 255. 47 | b = a * self.brightness + delta 48 | 49 | cv.ConvertScale(self.src_image, self.dst_image, a, b) 50 | cv.ShowImage("image", self.dst_image) 51 | 52 | cv.CalcArrHist([self.dst_image], self.hist) 53 | (min_value, max_value, _, _) = cv.GetMinMaxHistValue(self.hist) 54 | cv.Scale(self.hist.bins, self.hist.bins, float(self.hist_image.height) / max_value, 0) 55 | 56 | cv.Set(self.hist_image, cv.ScalarAll(255)) 57 | bin_w = round(float(self.hist_image.width) / hist_size) 58 | 59 | for i in range(hist_size): 60 | cv.Rectangle(self.hist_image, (int(i * bin_w), self.hist_image.height), 61 | (int((i + 1) * bin_w), self.hist_image.height - cv.Round(self.hist.bins[i])), 62 | cv.ScalarAll(0), -1, 8, 0) 63 | 64 | cv.ShowImage("histogram", self.hist_image) 65 | 66 | if __name__ == "__main__": 67 | # Load the source image. 68 | if len(sys.argv) > 1: 69 | src_image = cv.GetMat(cv.LoadImage(sys.argv[1], 0)) 70 | else: 71 | url = 'https://github.com/cdemel/OpenCV/blob/master/samples/cpp/baboon.jpg' 72 | filedata = urllib2.urlopen(url).read() 73 | imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1) 74 | cv.SetData(imagefiledata, filedata, len(filedata)) 75 | src_image = cv.DecodeImageM(imagefiledata, 0) 76 | 77 | dh = DemHist(src_image) 78 | 79 | cv.WaitKey(0) 80 | cv.DestroyAllWindows() 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /diplay_image.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from numpy import * 3 | from pylab import * 4 | 5 | import cv2 6 | 7 | # windows to display image 8 | cv2.namedWindow("Image") 9 | 10 | 11 | 12 | # read image 13 | image = cv2.imread('/home/cesco/Desktop/images/logo_steve.png') 14 | h,w = image.shape[:2] 15 | print h,w 16 | 17 | # save image 18 | cv2.imwrite('/home/cesco/Desktop/images/­result.png',image) 19 | 20 | # show image 21 | cv2.imshow("Image", image) 22 | 23 | # exit at closing of window 24 | cv2.waitKey(0) 25 | cv2.destroyAllWindows() 26 | -------------------------------------------------------------------------------- /display_image.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from numpy import * 3 | from pylab import * 4 | 5 | import cv2 6 | 7 | # windows to display image 8 | cv2.namedWindow("Image") 9 | 10 | 11 | 12 | # read image 13 | image = cv2.imread('/home/cesco/Desktop/images/logo_steve.png') 14 | h,w = image.shape[:2] 15 | print h,w 16 | 17 | # save image 18 | cv2.imwrite('/home/cesco/Desktop/images/­result.png',image) 19 | 20 | # show image 21 | cv2.imshow("Image", image) 22 | 23 | # exit at closing of window 24 | cv2.waitKey(0) 25 | cv2.destroyAllWindows() 26 | -------------------------------------------------------------------------------- /fast2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from matplotlib import pyplot as plt 3 | import cv2 4 | import scipy.fftpack 5 | 6 | 7 | # images imput 8 | img1 = cv2.imread('robVanPettenPhoto.png',0) 9 | img2 = cv2.imread('robVanPetten2.png',0) 10 | img3 = cv2.imread('cliffMautner.png',0) 11 | img4 = cv2.imread('bibliotequeHotelDeVille.png',0) 12 | img5 = cv2.imread('mugaMiyahara.png',0) 13 | img6 = cv2.imread('shinichiSato.png',0) 14 | 15 | 16 | 17 | 18 | # Images Input, layout, and transforms 19 | img_input = [img1, img2, img3, img4, img5, img6] 20 | picture_name = ['Rob Van Petten', 'Rob Van Petten','Cliff Mautner', 'Benjamin Antony Monn', \ 21 | 'Muga Miyahara', 'Shinichi Sato'] 22 | fft_images = [scipy.fftpack.ifft(x) for x in img_input] 23 | fft_shift = [scipy.fftpack.fftfreq(y) for y in fft_images] 24 | magnitude = [np.log(np.abs(z)+1) for z in fft_shift] 25 | 26 | for i in xrange(6): 27 | plt.subplot(2,3,i+1),plt.imshow(magnitude[i],cmap = 'gray') 28 | plt.title(picture_name[i]), plt.xticks([]), plt.yticks([]) 29 | 30 | plt.show() 31 | 32 | 33 | -------------------------------------------------------------------------------- /filters_cont.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | DELAY_CAPTION = 1500; 5 | DELAY_BLUR = 500; 6 | 7 | img = cv2.imread('lena.jpg') 8 | 9 | for i in xrange(1,31,2): 10 | blur = cv2.blur(img,(i,i)) 11 | string = 'blur : kernel size - '+str(i) 12 | cv2.putText(blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 13 | cv2.imshow('Blur',blur) 14 | cv2.waitKey(DELAY_BLUR) 15 | 16 | for i in xrange(1,31,2): 17 | gaussian_blur = cv2.GaussianBlur(img,(i,i),0) 18 | string = 'guassian_blur : kernel size - '+str(i) 19 | cv2.putText(gaussian_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 20 | cv2.imshow('Blur',gaussian_blur) 21 | cv2.waitKey(DELAY_BLUR) 22 | 23 | cv2.waitKey(DELAY_CAPTION) 24 | 25 | for i in xrange(1,31,2): 26 | median_blur = cv2.medianBlur(img,i) 27 | string = 'median_blur : kernel size - '+str(i) 28 | cv2.putText(median_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 29 | cv2.imshow('Blur',median_blur) 30 | cv2.waitKey(DELAY_BLUR) 31 | 32 | cv2.waitKey(DELAY_CAPTION) 33 | 34 | for i in xrange(1,31,2): # Remember, bilateral is a bit slow, so as value go higher, it takes long time 35 | bilateral_blur = cv2.bilateralFilter(img,i, i*2,i/2) 36 | string = 'bilateral_blur : kernel size - '+str(i) 37 | cv2.putText(bilateral_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 38 | cv2.imshow('Blur',bilateral_blur) 39 | cv2.waitKey(DELAY_BLUR) 40 | -------------------------------------------------------------------------------- /floodFill.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from numpy import * 3 | from pylab import * 4 | 5 | import cv2 6 | 7 | # read image 8 | filename = '/home/cesco/Desktop/images/pic3.png' 9 | im = cv2.imread(filename) 10 | h,w = im.shape[:2] 11 | 12 | # flood fill example 13 | diff = (6,6,6) 14 | mask = zeros((h+2,w+2),uint8) 15 | cv2.floodFill(im,mask,(10,10), (145,255,0),diff,diff) 16 | 17 | # show the result in an OpenCV window 18 | cv2.imshow('Flood Fill Image',im) 19 | cv2.waitKey(0) 20 | cv2.destroyAllWindows() 21 | 22 | # save the result 23 | cv2.imwrite('/home/cesco/Desktop/images/­result.jpg',im) 24 | -------------------------------------------------------------------------------- /installation.txt: -------------------------------------------------------------------------------- 1 | Tutorial on how to install OpenCV on 64bit Linux Ubuntu 13.04 . One of many tutorials to come. 2 | 3 | OpenCV was designed for computational efficiency and with a strong focus on real-time applications. Written in optimized C/C++, the library can take advantage of multi-core processing. Adopted all around the world, OpenCV has more than 47 thousand people in their user community and estimated number of downloads exceeding 6 million. Usage ranges from interactive art, to mines inspection, stitching maps on the web or through advanced robotics. 4 | 5 | Source Code Steps For Installation 6 | 1. Download Scipy Stack: 7 | 8 | sudo apt-get update 9 | sudo apt-get upgrade 10 | 11 | sudo apt-get install python-numpy python-scipy python-matplotlib ipython 12 | ipython- notebook python-pandas python-sympy python-nose 13 | 14 | 2. Download opencv: 15 | 16 | # install basic development environment 17 | 18 | sudo apt-get install build-essential cmake pkg-config 19 | 20 | # install opencv dependencies. ubuntu 13.04 ships with opencv 21 | # 2.4.2, which is close enough to 2.4.6 to pull in most of the 22 | # needed dependencies. If you still need the source code to get it, try to download it and extract it by 23 | following the following link: 24 | 25 | wget http://downloads.sourceforge.net/project/opencvlibrary/opencv-unix/2.4.6/OpenCV-2.4.6.tar.bz2 26 | 27 | sudo apt-get build-dep libopencv-dev 28 | 29 | # additional dependencies for java support 30 | 31 | sudo apt-get install default-jdk ant 32 | 33 | # for opengl support 34 | 35 | sudo apt-get install libgtkglext1-dev 36 | 37 | # compile opencv 38 | 39 | tar xzvf opencv-2.4.6.1.tar.gz 40 | cd opencv-2.4.6.1 41 | mkdir build 42 | cd build 43 | cmake -D CMAKE_BUILD_TYPE=RELEASE -D INSTALL_C_EXAMPLES=ON 44 | -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON 45 | -D WITH_QT=ON -D CMAKE_INSTALL_PREFIX=/usr/local 46 | -D WITH_OPENGL=ON -D WITH_V4L=ON 47 | -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_TBB=ON .. 48 | 49 | make 50 | sudo make install 51 | 52 | 53 | sudo nano /etc/ld.so.conf.d/opencv.conf 54 | /usr/local/lib 55 | sudo ldconfig 56 | sudo nano /etc/bash.bashrc 57 | PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig 58 | export PKG_CONFIG_PATH 59 | 60 | cd ~/OpenCV-2.4.6/samples/c 61 | chmod +x build_all.sh 62 | ./build_all.sh 63 | 64 | #try the examples and make sure they work 65 | 66 | python ~/OpenCV-2.4.6/samples/python2/turing.py 67 | 68 | Link for people that are having problems with the different versions of Ubuntu: http://answers.opencv.org/question/18226/opencv-java-build-error-in-ubuntu-1304/ 69 | 70 | Source Code For Future Tutorials - my dropbox account 71 | My Twitter https://twitter.com/Cesco345 72 | 73 | 74 | -------------------------------------------------------------------------------- /tutorial7_filters.py: -------------------------------------------------------------------------------- 1 | filters.py 2 | 3 | from PIL import Image 4 | from numpy import * 5 | from pylab import * 6 | 7 | import cv 8 | 9 | image = cv.LoadImage('miches.jpg',cv.CV_LOAD_IMA­GE_GRAYSCALE) 10 | 11 | # create the window 12 | cv.NamedWindow('Miches', cv.CV_WINDOW_AUTOSIZE) 13 | cv.ShowImage('Miches', image) # show the image 14 | cv.WaitKey() # close window 15 | 16 | 17 | # Sobel operator 18 | sobel = cv.CreateMat(image.height, image.width, cv.CV_32FC1) 19 | cv.Sobel(image,sobel,1,1,3) 20 | cv.ShowImage('Miches Sobel', sobel) 21 | cv.SaveImage('miches_sobel.jpg', sobel) 22 | cv.WaitKey() 23 | ________________________________________­___________________________ 24 | 25 | blur_smooth.py 26 | 27 | from PIL import Image 28 | from numpy import * 29 | from pylab import * 30 | 31 | import cv 32 | 33 | 34 | # this will load and show an image in gray scale 35 | image = cv.LoadImage('miches.jpg',cv.CV_LOAD_IMA­GE_GRAYSCALE) 36 | 37 | # original image during smoothing and subtraction 38 | blur_image = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 39 | 40 | 41 | # the original image during filtering 42 | cv.Smooth(image, blur_image, cv.CV_BLUR, 15, 15) 43 | fil = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 44 | 45 | 46 | # subtraction of the original minus the filtered one 47 | cv.AbsDiff(image,blur_image,fil) 48 | cv.ShowImage('Image', fil) 49 | cv.WaitKey() 50 | cv.SaveImage('result_image.jpg', fil) 51 | ________________________________________­______________________________ 52 | 53 | 54 | 55 | from PIL import Image 56 | from numpy import * 57 | from pylab import * 58 | 59 | import cv 60 | 61 | im = cv.LoadImageM("miches.jpg", 1) 62 | dst = cv.CreateImage(cv.GetSize(im), cv.IPL_DEPTH_16S, 3) 63 | laplace = cv.Laplace(im, dst) 64 | cv.SaveImage("miches_laplace.png", dst) 65 | -------------------------------------------------------------------------------- /tutorial_10.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from numpy import * 3 | from pylab import * 4 | 5 | import urllib 6 | import cv2 7 | 8 | 9 | url = 'http://vis-www.cs.umass.edu/lfw/images/Bob_Bowlsby/Bob_Bowlsby_0001.jpg' 10 | urllib.urlretrieve(url,'filename.png') 11 | 12 | # windows to display image 13 | cv2.namedWindow("Image") 14 | image = cv2.imread('filename.png') 15 | 16 | h,w = image.shape[:2] 17 | print h,w 18 | 19 | # show image 20 | cv2.imshow("Image", image) 21 | 22 | # save image 23 | cv2.imwrite('/home/cesco/Desktop/images/retrieve_result.png',image) 24 | 25 | 26 | 27 | # exit at closing of window 28 | cv2.waitKey(0) 29 | cv2.destroyAllWindows() 30 | -------------------------------------------------------------------------------- /tutorial_11.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from numpy import * 3 | from pylab import * 4 | from wand.image import Image 5 | from wand.display import display 6 | import urllib 7 | import cv2 8 | 9 | 10 | url = 'http://vis-www.cs.umass.edu/lfw/images/Bob_Bowlsby/Bob_Bowlsby_0001.jpg' 11 | urllib.urlretrieve(url,'bob.png') 12 | 13 | 14 | with Image(filename='bob.png') as img: 15 | print(img.size) 16 | for r in 1, 2, 3: 17 | with img.clone() as i: 18 | i.resize(int(i.width * r * 0.25), int(i.height * r * 0.25)) 19 | i.rotate(90 * r) 20 | i.save(filename='bob-{0}.png'.format(r)) 21 | display(i) 22 | 23 | # windows to display image 24 | cv2.namedWindow("Image") 25 | image = cv2.imread('bob.png') 26 | 27 | h,w = image.shape[:2] 28 | print h,w 29 | 30 | # show image 31 | cv2.imshow("Image", image) 32 | 33 | # save image 34 | cv2.imwrite('/home/cesco/Desktop/python/bob.png',image) 35 | -------------------------------------------------------------------------------- /tutorial_12.py: -------------------------------------------------------------------------------- 1 | from pylab import * 2 | from numpy import * 3 | from scipy.ndimage import filters 4 | import harris 5 | import cv2 6 | from PIL import Image 7 | import harris_run 8 | 9 | 10 | 11 | im = array(Image.open('lady_in_red_big.jpg').convert('L')) 12 | harrisim = harris.compute_harris_response(im) 13 | filtered_coords = harris.get_harris_points(harrisim,6) 14 | harris.plot_harris_points(im, filtered_coords) 15 | 16 | 17 | -------------------------------------------------------------------------------- /tutorial_12b.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from pylab import * 3 | from numpy import * 4 | from scipy.ndimage import filters 5 | 6 | 7 | def compute_harris_response(im,sigma=3): 8 | """ Compute the Harris corner detector response function 9 | for each pixel in a graylevel image. """ 10 | 11 | # derivatives 12 | imx = zeros(im.shape) 13 | filters.gaussian_filter(im, (sigma,sigma), (0,1), imx) 14 | imy = zeros(im.shape) 15 | filters.gaussian_filter(im, (sigma,sigma), (1,0), imy) 16 | 17 | # compute components of the Harris matrix 18 | Wxx = filters.gaussian_filter(imx*imx,sigma) 19 | Wxy = filters.gaussian_filter(imx*imy,sigma) 20 | Wyy = filters.gaussian_filter(imy*imy,sigma) 21 | 22 | # determinant and trace 23 | Wdet = Wxx*Wyy - Wxy**2 24 | Wtr = Wxx + Wyy 25 | 26 | return Wdet / (Wtr*Wtr) 27 | 28 | 29 | def get_harris_points(harrisim,min_dist=10,threshold=0.1): 30 | """ Return corners from a Harris response image 31 | min_dist is the minimum number of pixels separating 32 | corners and image boundary. """ 33 | 34 | # find top corner candidates above a threshold 35 | corner_threshold = harrisim.max() * threshold 36 | harrisim_t = (harrisim > corner_threshold) * 1 37 | 38 | # get coordinates of candidates 39 | coords = array(harrisim_t.nonzero()).T 40 | 41 | # ...and their values 42 | candidate_values = [harrisim[c[0],c[1]] for c in coords] 43 | 44 | # sort candidates 45 | index = argsort(candidate_values) 46 | 47 | # store allowed point locations in array 48 | allowed_locations = zeros(harrisim.shape) 49 | allowed_locations[min_dist:-min_dist,min_dist:-min_dist] = 1 50 | 51 | # select the best points taking min_distance into account 52 | filtered_coords = [] 53 | for i in index: 54 | if allowed_locations[coords[i,0],coords[i,1]] == 1: 55 | filtered_coords.append(coords[i]) 56 | allowed_locations[(coords[i,0]-min_dist):(coords[i,0]+min_dist), 57 | (coords[i,1]-min_dist):(coords[i,1]+min_dist)] = 0 58 | 59 | return filtered_coords 60 | 61 | 62 | def plot_harris_points(image,filtered_coords): 63 | """ Plots corners found in image. """ 64 | 65 | figure() 66 | gray() 67 | imshow(image) 68 | plot([p[1] for p in filtered_coords], 69 | [p[0] for p in filtered_coords],'*') 70 | axis('off') 71 | show() 72 | 73 | 74 | def get_descriptors(image,filtered_coords,wid=5): 75 | """ For each point return pixel values around the point 76 | using a neighbourhood of width 2*wid+1. (Assume points are 77 | extracted with min_distance > wid). """ 78 | 79 | desc = [] 80 | for coords in filtered_coords: 81 | patch = image[coords[0]-wid:coords[0]+wid+1, 82 | coords[1]-wid:coords[1]+wid+1].flatten() 83 | desc.append(patch) 84 | 85 | return desc 86 | 87 | 88 | def match(desc1,desc2,threshold=0.5): 89 | """ For each corner point descriptor in the first image, 90 | select its match to second image using 91 | normalized cross correlation. """ 92 | 93 | n = len(desc1[0]) 94 | 95 | # pair-wise distances 96 | d = -ones((len(desc1),len(desc2))) 97 | for i in range(len(desc1)): 98 | for j in range(len(desc2)): 99 | d1 = (desc1[i] - mean(desc1[i])) / std(desc1[i]) 100 | d2 = (desc2[j] - mean(desc2[j])) / std(desc2[j]) 101 | ncc_value = sum(d1 * d2) / (n-1) 102 | if ncc_value > threshold: 103 | d[i,j] = ncc_value 104 | 105 | ndx = argsort(-d) 106 | matchscores = ndx[:,0] 107 | 108 | return matchscores 109 | 110 | 111 | def match_twosided(desc1,desc2,threshold=0.5): 112 | """ Two-sided symmetric version of match(). """ 113 | 114 | matches_12 = match(desc1,desc2,threshold) 115 | matches_21 = match(desc2,desc1,threshold) 116 | 117 | ndx_12 = where(matches_12 >= 0)[0] 118 | 119 | # remove matches that are not symmetric 120 | for n in ndx_12: 121 | if matches_21[matches_12[n]] != n: 122 | matches_12[n] = -1 123 | 124 | return matches_12 125 | 126 | 127 | def appendimages(im1,im2): 128 | """ Return a new image that appends the two images side-by-side. """ 129 | 130 | # select the image with the fewest rows and fill in enough empty rows 131 | rows1 = im1.shape[0] 132 | rows2 = im2.shape[0] 133 | 134 | if rows1 < rows2: 135 | im1 = concatenate((im1,zeros((rows2-rows1,im1.shape[1]))),axis=0) 136 | elif rows1 > rows2: 137 | im2 = concatenate((im2,zeros((rows1-rows2,im2.shape[1]))),axis=0) 138 | # if none of these cases they are equal, no filling needed. 139 | 140 | return concatenate((im1,im2), axis=1) 141 | 142 | 143 | def plot_matches(im1,im2,locs1,locs2,matchscores,show_below=True): 144 | """ Show a figure with lines joining the accepted matches 145 | input: im1,im2 (images as arrays), locs1,locs2 (feature locations), 146 | matchscores (as output from 'match()'), 147 | show_below (if images should be shown below matches). """ 148 | 149 | im3 = appendimages(im1,im2) 150 | if show_below: 151 | im3 = vstack((im3,im3)) 152 | 153 | imshow(im3) 154 | 155 | cols1 = im1.shape[1] 156 | for i,m in enumerate(matchscores): 157 | if m>0: 158 | plot([locs1[i][1],locs2[m][1]+cols1],[locs1[i][0],locs2[m][0]],'c') 159 | axis('off') 160 | -------------------------------------------------------------------------------- /tutorial_12c.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import cv 3 | 4 | r = requests.get('http://www.autoshowup.com/stockimg/gable-of-a-half-timbered-house-in-black-and-white-in-a-traditional-german-village.jpg') 5 | with open('imported_pic.jpg','wb') as f: 6 | f.write(r.content) 7 | 8 | #r = requests.get('http://www.free-macrame-patterns.com/image-files/diamond-stitch-medium.jpg') 9 | #with open('imported_pic.jpg','wb') as f: 10 | # f.write(r.content) 11 | 12 | #imcolor = cv.LoadImage('lady_in_red_big.jpg') 13 | #image = cv.LoadImage('lady_in_red_big.jpg',cv.CV_LOAD_IMAGE_GRAYSCALE) 14 | 15 | 16 | imcolor = cv.LoadImage('imported_pic.jpg') 17 | image = cv.LoadImage('imported_pic.jpg',cv.CV_LOAD_IMAGE_GRAYSCALE) 18 | cornerMap = cv.CreateMat(image.height, image.width, cv.CV_32FC1) 19 | 20 | 21 | 22 | # OpenCV corner detection 23 | cv.CornerHarris(image,cornerMap,3) 24 | 25 | for y in range(0, image.height): 26 | for x in range(0, image.width): 27 | harris = cv.Get2D(cornerMap, y, x) # get the x,y value 28 | 29 | # check the corner detector response 30 | if harris[0] > 10e-06: 31 | # draw a small circle on the original image 32 | cv.Circle(imcolor,(x,y),1,cv.RGB(35, 0,165)) 33 | 34 | cv.NamedWindow('Harris Corner Image', cv.CV_WINDOW_AUTOSIZE) 35 | cv.ShowImage('Harris Corner Image', imcolor) # show the image 36 | cv.SaveImage('harris_corner_image.jpg', imcolor) 37 | cv.WaitKey() 38 | 39 | -------------------------------------------------------------------------------- /tutorial_13.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from matplotlib import pyplot as plt 3 | from scipy import ndimage 4 | from skimage import filter 5 | import cv2 6 | 7 | 8 | 9 | img = cv2.imread('lady_in_red_big.jpg',0) 10 | im = ndimage.gaussian_filter(img, 4) 11 | im += 0.2 * np.random.random(img.shape) 12 | 13 | # Canny filter for two different values of sigma 14 | edges1 = filter.canny(im) 15 | edges2 = filter.canny(im, sigma=3) 16 | 17 | # data display 18 | plt.figure(figsize=(8, 3)) 19 | 20 | plt.subplot(131) 21 | plt.imshow(im, cmap=plt.cm.jet) 22 | plt.axis('off') 23 | plt.title('noisy image', fontsize=20) 24 | 25 | plt.subplot(132) 26 | plt.imshow(edges1, cmap=plt.cm.gray) 27 | plt.axis('off') 28 | plt.title('Canny filter, $\sigma=1$', fontsize=20) 29 | 30 | plt.subplot(133) 31 | plt.imshow(edges2, cmap=plt.cm.gray) 32 | plt.axis('off') 33 | plt.title('Canny filter, $\sigma=3$', fontsize=20) 34 | 35 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, 36 | bottom=0.02, left=0.02, right=0.98) 37 | 38 | plt.show() 39 | 40 | 41 | # And now using OpenCV, with the above cv2 import 42 | img = cv2.imread('lady_in_red_big.jpg',0) 43 | edges11 = cv2.Canny(img,100,200) 44 | edges22 = cv2.Canny(img,200,300) 45 | 46 | 47 | plt.subplot(131) 48 | plt.imshow(img,cmap='gray') 49 | plt.axis('off') 50 | plt.title('Gray Image', fontsize=20) 51 | 52 | 53 | plt.subplot(132) 54 | plt.imshow(edges11,cmap = 'gray') 55 | plt.axis('off') 56 | plt.title('Lower MinVal', fontsize=20) 57 | 58 | 59 | plt.subplot(133) 60 | plt.imshow(edges22,cmap = 'gray') 61 | plt.axis('off') 62 | plt.title('Higher MinVal', fontsize=20) 63 | 64 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, 65 | bottom=0.02, left=0.02, right=0.98) 66 | plt.show() 67 | 68 | -------------------------------------------------------------------------------- /tutorial_14.py: -------------------------------------------------------------------------------- 1 | from pylab import * 2 | from numpy import * 3 | from scipy.ndimage import filters 4 | import harris 5 | import cv2 6 | from PIL import Image 7 | import harris_run 8 | 9 | 10 | 11 | im = array(Image.open('lady_in_red_big.jpg').convert('L')) 12 | harrisim = harris.compute_harris_response(im) 13 | filtered_coords = harris.get_harris_points(harrisim,6) 14 | harris.plot_harris_points(im, filtered_coords) 15 | 16 | 17 | -------------------------------------------------------------------------------- /tutorial_14Harris.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from pylab import * 3 | from numpy import * 4 | from scipy.ndimage import filters 5 | 6 | 7 | def compute_harris_response(im,sigma=3): 8 | """ Compute the Harris corner detector response function 9 | for each pixel in a graylevel image. """ 10 | 11 | # derivatives 12 | imx = zeros(im.shape) 13 | filters.gaussian_filter(im, (sigma,sigma), (0,1), imx) 14 | imy = zeros(im.shape) 15 | filters.gaussian_filter(im, (sigma,sigma), (1,0), imy) 16 | 17 | # compute components of the Harris matrix 18 | Wxx = filters.gaussian_filter(imx*imx,sigma) 19 | Wxy = filters.gaussian_filter(imx*imy,sigma) 20 | Wyy = filters.gaussian_filter(imy*imy,sigma) 21 | 22 | # determinant and trace 23 | Wdet = Wxx*Wyy - Wxy**2 24 | Wtr = Wxx + Wyy 25 | 26 | return Wdet / (Wtr*Wtr) 27 | 28 | 29 | def get_harris_points(harrisim,min_dist=10,threshold=0.1): 30 | """ Return corners from a Harris response image 31 | min_dist is the minimum number of pixels separating 32 | corners and image boundary. """ 33 | 34 | # find top corner candidates above a threshold 35 | corner_threshold = harrisim.max() * threshold 36 | harrisim_t = (harrisim > corner_threshold) * 1 37 | 38 | # get coordinates of candidates 39 | coords = array(harrisim_t.nonzero()).T 40 | 41 | # ...and their values 42 | candidate_values = [harrisim[c[0],c[1]] for c in coords] 43 | 44 | # sort candidates 45 | index = argsort(candidate_values) 46 | 47 | # store allowed point locations in array 48 | allowed_locations = zeros(harrisim.shape) 49 | allowed_locations[min_dist:-min_dist,min_dist:-min_dist] = 1 50 | 51 | # select the best points taking min_distance into account 52 | filtered_coords = [] 53 | for i in index: 54 | if allowed_locations[coords[i,0],coords[i,1]] == 1: 55 | filtered_coords.append(coords[i]) 56 | allowed_locations[(coords[i,0]-min_dist):(coords[i,0]+min_dist), 57 | (coords[i,1]-min_dist):(coords[i,1]+min_dist)] = 0 58 | 59 | return filtered_coords 60 | 61 | 62 | def plot_harris_points(image,filtered_coords): 63 | """ Plots corners found in image. """ 64 | 65 | figure() 66 | gray() 67 | imshow(image) 68 | plot([p[1] for p in filtered_coords], 69 | [p[0] for p in filtered_coords],'*') 70 | axis('off') 71 | show() 72 | 73 | 74 | def get_descriptors(image,filtered_coords,wid=5): 75 | """ For each point return pixel values around the point 76 | using a neighbourhood of width 2*wid+1. (Assume points are 77 | extracted with min_distance > wid). """ 78 | 79 | desc = [] 80 | for coords in filtered_coords: 81 | patch = image[coords[0]-wid:coords[0]+wid+1, 82 | coords[1]-wid:coords[1]+wid+1].flatten() 83 | desc.append(patch) 84 | 85 | return desc 86 | 87 | 88 | def match(desc1,desc2,threshold=0.5): 89 | """ For each corner point descriptor in the first image, 90 | select its match to second image using 91 | normalized cross correlation. """ 92 | 93 | n = len(desc1[0]) 94 | 95 | # pair-wise distances 96 | d = -ones((len(desc1),len(desc2))) 97 | for i in range(len(desc1)): 98 | for j in range(len(desc2)): 99 | d1 = (desc1[i] - mean(desc1[i])) / std(desc1[i]) 100 | d2 = (desc2[j] - mean(desc2[j])) / std(desc2[j]) 101 | ncc_value = sum(d1 * d2) / (n-1) 102 | if ncc_value > threshold: 103 | d[i,j] = ncc_value 104 | 105 | ndx = argsort(-d) 106 | matchscores = ndx[:,0] 107 | 108 | return matchscores 109 | 110 | 111 | def match_twosided(desc1,desc2,threshold=0.5): 112 | """ Two-sided symmetric version of match(). """ 113 | 114 | matches_12 = match(desc1,desc2,threshold) 115 | matches_21 = match(desc2,desc1,threshold) 116 | 117 | ndx_12 = where(matches_12 >= 0)[0] 118 | 119 | # remove matches that are not symmetric 120 | for n in ndx_12: 121 | if matches_21[matches_12[n]] != n: 122 | matches_12[n] = -1 123 | 124 | return matches_12 125 | 126 | 127 | def appendimages(im1,im2): 128 | """ Return a new image that appends the two images side-by-side. """ 129 | 130 | # select the image with the fewest rows and fill in enough empty rows 131 | rows1 = im1.shape[0] 132 | rows2 = im2.shape[0] 133 | 134 | if rows1 < rows2: 135 | im1 = concatenate((im1,zeros((rows2-rows1,im1.shape[1]))),axis=0) 136 | elif rows1 > rows2: 137 | im2 = concatenate((im2,zeros((rows1-rows2,im2.shape[1]))),axis=0) 138 | # if none of these cases they are equal, no filling needed. 139 | 140 | return concatenate((im1,im2), axis=1) 141 | 142 | 143 | def plot_matches(im1,im2,locs1,locs2,matchscores,show_below=True): 144 | """ Show a figure with lines joining the accepted matches 145 | input: im1,im2 (images as arrays), locs1,locs2 (feature locations), 146 | matchscores (as output from 'match()'), 147 | show_below (if images should be shown below matches). """ 148 | 149 | im3 = appendimages(im1,im2) 150 | if show_below: 151 | im3 = vstack((im3,im3)) 152 | 153 | imshow(im3) 154 | 155 | cols1 = im1.shape[1] 156 | for i,m in enumerate(matchscores): 157 | if m>0: 158 | plot([locs1[i][1],locs2[m][1]+cols1],[locs1[i][0],locs2[m][0]],'c') 159 | axis('off') 160 | -------------------------------------------------------------------------------- /tutorial_8: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | DELAY_CAPTION = 1500; 5 | DELAY_BLUR = 500; 6 | 7 | img = cv2.imread('lena.jpg') 8 | 9 | for i in xrange(1,31,2): 10 | blur = cv2.blur(img,(i,i)) 11 | string = 'blur : kernel size - '+str(i) 12 | cv2.putText(blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 13 | cv2.imshow('Blur',blur) 14 | cv2.waitKey(DELAY_BLUR) 15 | 16 | for i in xrange(1,31,2): 17 | gaussian_blur = cv2.GaussianBlur(img,(i,i),0) 18 | string = 'guassian_blur : kernel size - '+str(i) 19 | cv2.putText(gaussian_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 20 | cv2.imshow('Blur',gaussian_blur) 21 | cv2.waitKey(DELAY_BLUR) 22 | 23 | cv2.waitKey(DELAY_CAPTION) 24 | 25 | for i in xrange(1,31,2): 26 | median_blur = cv2.medianBlur(img,i) 27 | string = 'median_blur : kernel size - '+str(i) 28 | cv2.putText(median_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 29 | cv2.imshow('Blur',median_blur) 30 | cv2.waitKey(DELAY_BLUR) 31 | 32 | cv2.waitKey(DELAY_CAPTION) 33 | 34 | for i in xrange(1,31,2): # Remember, bilateral is a bit slow, so as value go higher, it takes long time 35 | bilateral_blur = cv2.bilateralFilter(img,i, i*2,i/2) 36 | string = 'bilateral_blur : kernel size - '+str(i) 37 | cv2.putText(bilateral_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 38 | cv2.imshow('Blur',bilateral_blur) 39 | cv2.waitKey(DELAY_BLUR) 40 | -------------------------------------------------------------------------------- /tutorial_8.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | DELAY_CAPTION = 1500; 5 | DELAY_BLUR = 500; 6 | 7 | img = cv2.imread('lena.jpg') 8 | 9 | for i in xrange(1,31,2): 10 | blur = cv2.blur(img,(i,i)) 11 | string = 'blur : kernel size - '+str(i) 12 | cv2.putText(blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 13 | cv2.imshow('Blur',blur) 14 | cv2.waitKey(DELAY_BLUR) 15 | 16 | for i in xrange(1,31,2): 17 | gaussian_blur = cv2.GaussianBlur(img,(i,i),0) 18 | string = 'guassian_blur : kernel size - '+str(i) 19 | cv2.putText(gaussian_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 20 | cv2.imshow('Blur',gaussian_blur) 21 | cv2.waitKey(DELAY_BLUR) 22 | 23 | cv2.waitKey(DELAY_CAPTION) 24 | 25 | for i in xrange(1,31,2): 26 | median_blur = cv2.medianBlur(img,i) 27 | string = 'median_blur : kernel size - '+str(i) 28 | cv2.putText(median_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 29 | cv2.imshow('Blur',median_blur) 30 | cv2.waitKey(DELAY_BLUR) 31 | 32 | cv2.waitKey(DELAY_CAPTION) 33 | 34 | for i in xrange(1,31,2): # Remember, bilateral is a bit slow, so as value go higher, it takes long time 35 | bilateral_blur = cv2.bilateralFilter(img,i, i*2,i/2) 36 | string = 'bilateral_blur : kernel size - '+str(i) 37 | cv2.putText(bilateral_blur,string,(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255)) 38 | cv2.imshow('Blur',bilateral_blur) 39 | cv2.waitKey(DELAY_BLUR) 40 | -------------------------------------------------------------------------------- /tutorial_9.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import subprocess 4 | import argparse 5 | 6 | # parse command line arguments 7 | 8 | parser = argparse.ArgumentParser(description='Bat­ch change filenames.') 9 | parser.add_argument('inputFileName', metavar='baseNameIn') 10 | parser.add_argument('outputFileName', metavar='baseNameOut') 11 | args = parser.parse_args() 12 | 13 | # Run a bash cmd and send output to a list separated by line 14 | 15 | def runBash(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) out = p.stdout.read().strip() return out.split('\n') 16 | 17 | # Change new function 18 | 19 | def changePictureName(oldPictureName, newPictureNameBase): temp = oldPictureName.split('.') newPictureName = newPictureNameBase + '.' + temp[1] + '.' + temp[2] subprocess.call(["mv", oldPictureName, newPictureName]) 20 | 21 | # Change names of all files matching base 22 | 23 | 24 | def changeAllPictureNames(oldPictureNameBase­, newPictureNameBase): files = runBash("ls") for afile in files: if afile.split('.')[0] == oldPictureNameBase: changePictureName(afile, newPictureNameBase) 25 | 26 | changeAllPictureNames(args.inputFileName­, args.outputFileName) 27 | 28 | groupPictureRenameRE.py 29 | 30 | #!/usr/bin/env python 31 | 32 | import subprocess 33 | import argparse 34 | import re 35 | 36 | # parse command line arguments 37 | 38 | parser = argparse.ArgumentParser(description='Bat­ch change filenames.') 39 | parser.add_argument('inputFileName', metavar='baseNameIn') 40 | parser.add_argument('outputFileName', metavar='baseNameOut') 41 | args = parser.parse_args() 42 | 43 | 44 | # Run a bash cmd and send output to a list separated by line 45 | 46 | def runBash(cmd): 47 | p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) 48 | out = p.stdout.read().strip() 49 | return out.split('\n') 50 | 51 | # Change new function 52 | 53 | def changePictureName(oldPictureName, newPictureNameBase): 54 | temp = re.split('([0-9]+)', oldPictureName) 55 | newPictureName = newPictureNameBase + temp[1] + temp[2] 56 | subprocess.call(["mv", oldPictureName, newPictureName]) 57 | 58 | # Change names of all files matching base 59 | 60 | 61 | def changeAllPictureNames(oldPictureNameBase­, newPictureNameBase): 62 | files = runBash("ls") 63 | 64 | for afile in files: 65 | temp = re.split('([0-9]+)', afile) 66 | if temp[0] == oldPictureNameBase: 67 | changePictureName(afile, newPictureNameBase) 68 | 69 | changeAllPictureNames(args.inputFileName­,args.outputFileName) 70 | -------------------------------------------------------------------------------- /yellow_rose.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from numpy import * 3 | from pylab import * 4 | 5 | import cv 6 | 7 | im = cv.LoadImageM("yellow_rose.jpg") 8 | print type(im) 9 | cv.NamedWindow("Rose", cv.CV_WINDOW_AUTOSIZE ) 10 | cv.ShowImage("New Rose", im) 11 | cv.WaitKey(10000) 12 | cv.SaveImage("new_yellow_rose.png", im) 13 | cv.DestroyWindow("Rose") 14 | 15 | --------------------------------------------------------------------------------