#print n_p.shape if n_p.size != 0: v = np.concatenate((v, n_p)) f += 1 else: f += 1 v = np.concatenate((v, pts)) print "No of circles detected : {0}.".format(num_of_circles) plt.figure("Detecting Circles and Marking") #Original Image plt.subplot(3, 2, 1) plt.title('Original Image') plt.imshow(u.convertPlot(im)) plt.xticks([]), plt.yticks([]) #GrayScale Image plt.subplot(3, 2, 2) plt.gray() plt.title('Grayscale Image') plt.imshow(gray) plt.xticks([]), plt.yticks([]) #Gaussian Blurred Image plt.subplot(3, 2, 3) plt.gray() plt.title('Blurred Image') plt.imshow(fgray) plt.xticks([]), plt.yticks([])
gray = np.float32(gray) dst = cv2.cornerHarris(gray,2,3,0.04) #result dilated to mark the corners,i.e we dilate the corner pixels kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(20,20)) dst = cv2.dilate(dst,None) #thresholding for optimal value, it depends on the image ret,dst = cv2.threshold(dst,0.045*dst.max(),255,0) dst = np.uint8(dst) #finding the centroid ret,labels,stats,centroids = cv2.connectedComponentsWithStats(dst) #define the criteria to stop and refine the corners criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001) corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),(-1,-1),criteria) #Now we draw these res = np.hstack((centroids,corners)) res = np.int0(res) img[res[:,1],res[:,0]] = [0,0,255] img[res[:,3],res[:,2]] = [0,255,0] """ plt.figure("Harris Corner Detection"); plt.imshow(utils.convertPlot(img)) plt.show()
print image.shape #when resizing an image the aspect ratio must be maintained r = 100.0 / image.shape[1] #now if the x is fixed as 100 # y becomes r*y dim = (100, int(image.shape[0] * r)) #performig the resize resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA) subplot(141) title('Original Image') imshow(convertPlot(image)) subplot(142) title('Resized Image (Maintains Aspect ratio)') imshow(convertPlot(resized)) #rotating the image (h, w) = image.shape[:2] center = (w / 2, h / 2) #rotating the image by 18- degress M = cv2.getRotationMatrix2D(center, 180, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) subplot(143) title('Rotated Image 180') imshow(convertPlot(rotated))
'snaps/I8.jpg', 'snaps/I9.jpg', 'snaps/I10.jpg' ] image = cv2.imread(IMAGE_PATHS[0]) marker = find_marker(image) focalLength = (marker[1][0]*KNOWN_DISTANCE)/KNOWN_WIDTH #looping over the images,to get the distance for imagePath in IMAGE_PATHS: image = cv2.imread(imagePath) marker = find_marker(image) inches = distance_from_camera(KNOWN_WIDTH, focalLength, marker[1][0]) box = np.int0(cv2.boxPoints(marker)) cv2.drawContours(image, [box], -1, (0, 255, 0), 2) cv2.putText(image, "%.2fft" % (inches / 12), (image.shape[1] - 200, image.shape[0] - 20), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (0, 255, 0), 3) plt.figure("Distance from Camera") plt.imshow(utils.convertPlot(image)) plt.show() cv2.waitKey(2000)
import numpy as np if __name__ == '__main__': face_cascade = cv2.CascadeClassifier('/home/riaz/opencv-3.0.0/data/haarcascades/haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('/home/riaz/opencv-3.0.0/data/haarcascades/haarcascade_eye.xml') img = cv2.imread('book.jpg') copy = img.copy() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray) for (ex, ey, ew, eh) in eyes: cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2) plt.figure("Face Detection") plt.subplot(1, 2, 1) plt.imshow(u.convertPlot(copy)) plt.xticks([]), plt.yticks([]) plt.subplot(1, 2, 2) plt.imshow(u.convertPlot(img)) plt.xticks([]), plt.yticks([]) plt.show()
for c in cnts: #approximate the contour peri = cv2.arcLength(c, True) #if the approx poly has 4 points,we can conclude the contour to be the screen, since this also happens to be the largest contour approx = cv2.approxPolyDP(c, 0.02 * peri, True) if len(approx) == 4: scrnCnt = approx break #OpenCV comes with a draw contour functionality to mark these contours #we use that the library function to mark the contours print scrnCnt cv2.drawContours(copy, [scrnCnt], -1, (0, 255, 0), 3) plt.figure("Recognizing rectangle") #plt.gray() plt.subplot(1, 3, 1) plt.imshow(utils.convertPlot(im)) plt.subplot(1, 3, 2) plt.imshow(edged) plt.subplot(1, 3, 3) plt.imshow(utils.convertPlot(copy)) plt.show()
rect = ( 50, 50, 450, 290 ) #this rect can be made interactive later, by selecting using the mouse """ Parameter: 1.image 2. mask (0 filled image mask) 3. rect (of interest) 4. background model 5. foreground model 6. interationCount - to have a better segmentation 7. mode: since we use a rectangle box: cv2.GC_INIT_WITH_RECT """ img = utils.convertPlot(img) cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8') img = img * mask2[:, :, np.newaxis] newmask = cv2.imread('grabCut_manual.png', 0) #whatever is marked white is foreground ,mask = 1 #whatever is marked black is background , mask = 0 mask[newmask == 0] = 0 #background mask[newmask == 255] = 1 #foreground mask, bgdModel, fgdModel = cv2.grabCut(img, mask, None, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_MASK) mask = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
fgdModel= np.zeros((1,65),np.float64) rect = (50,50,450,290 )#this rect can be made interactive later, by selecting using the mouse """ Parameter: 1.image 2. mask (0 filled image mask) 3. rect (of interest) 4. background model 5. foreground model 6. interationCount - to have a better segmentation 7. mode: since we use a rectangle box: cv2.GC_INIT_WITH_RECT """ img = utils.convertPlot(img) cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') img = img*mask2[:,:,np.newaxis] newmask = cv2.imread('grabCut_manual.png',0) #whatever is marked white is foreground ,mask = 1 #whatever is marked black is background , mask = 0 mask[newmask == 0] = 0 #background mask[newmask == 255] = 1 #foreground mask, bgdModel, fgdModel = cv2.grabCut(img,mask,None,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK) mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
print image.shape #when resizing an image the aspect ratio must be maintained r = 100.0/image.shape[1] #now if the x is fixed as 100 # y becomes r*y dim = (100, int(image.shape[0]*r)) #performig the resize resized = cv2.resize(image,dim,interpolation=cv2.INTER_AREA) subplot(141) title('Original Image') imshow(convertPlot(image)) subplot(142) title('Resized Image (Maintains Aspect ratio)') imshow(convertPlot(resized)) #rotating the image (h,w) = image.shape[:2] center = (w/2,h/2) #rotating the image by 18- degress M = cv2.getRotationMatrix2D(center,180,1.0) rotated=cv2.warpAffine(image,M,(w,h)) subplot(143) title('Rotated Image 180') imshow(convertPlot(rotated))
#Using naive Harris Corner Detection with Kernel size 20 import cv2 import numpy as np from matplotlib import pyplot as plt import utils filename = "chessBoard.jpg" img = cv2.imread(filename) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = np.float32(gray) dst = cv2.cornerHarris(gray, 2, 3, 0.04) #result dilated to mark the corners,i.e we dilate the corner pixels kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20, 20)) dst = cv2.dilate(dst, kernel) #thresholding for optimal value, it depends on the image img[dst > 0.045 * dst.max()] = [255, 0, 0 ] #put blue color for pixels, > 0.01*dst.max() plt.figure("Harris Corner Detection") plt.imshow(utils.convertPlot(img)) plt.show()
#This part does blob detection, sbd = cv2.SimpleBlobDetector_create() #we store the detected blobs or keypoints in the image kpts = sbd.detect(smooth) #now we plot these keypoints in the image blob = mark_blobs(smooth, kpts, (0, 255, 0), 10) ret, normal = cv2.threshold(smooth, 100, 255, cv2.THRESH_BINARY) inv = 255 - normal """ plt.figure("Detect book in an image") plt.subplot(2, 3, 1) plt.imshow(utils.convertPlot(im)) plt.xticks([]), plt.yticks([]) plt.subplot(2, 3, 2) plt.gray() plt.imshow(smooth) plt.xticks([]), plt.yticks([]) plt.subplot(2, 3, 3) plt.imshow(thres) plt.xticks([]), plt.yticks([]) plt.subplot(2, 3, 4) plt.gray() plt.imshow(canny)