Software Design Principles
OpenCV BasicIntroductsion and InstlationBasic Image OpreationImage Read and WriteUnderatnding image stauctures and channelsCreating Images and MasksExtracting channels of imagesColor Conversion RGB to GRAYblur, kernel, dilate and erodeResize and RotateReading Videos:Painting over video.Object Detection.Binary ThresholdAdaptive ThresholdOperation on HSV and filtersContourscontourArea, perimeter and centrold.Canny Edges detction:Object detction ModelsmatchTemplate to detcet objectsDetection of face using haarcascade_frontalfaceDetection of eye using haarcascade_eyeComputer Vision Projects
OpenCV Basic
Introductsion and Instlation
* Bullete points
* Bullate Points
Basic Image Opreation
Image Read and Write
import numpy as np import cv2 # Read img img = cv2.imread("opencv-logo.png") # Open windows cv2.namedWindow("Image",cv2.WINDOW_NORMAL) cv2.imshow("Image",img) # Wait for key cv2.waitKey(0) #Write cv2.imwrite("output.jpg",img)
Underatnding image stauctures and channels
import numpy as np import cv2 img = cv2.imread("opencv-logo.png", 1) # Printing basic infomation print(img) #Three 2D Array as numpy as BGR print(type(img)) # <class 'numpy.ndarray'> print(img.shape) # (739, 600, 3) print(img.dtype) # dtype('uint8') print(img.size) # Extraling one channels img[:, :, 0] # get only the blue
Creating Images and Masks
import numpy as np import cv2 # A Black image black = np.zeros([150,200,1],'uint8') cv2.imshow("Black",black) print(black[0,0,:]) # A white Image ones = np.ones([150,200,3],'uint8') cv2.imshow("Ones",ones) # this near black print(ones[0,0,:]) white = np.ones([150,200,3],'uint16') white *= (2**16-1) cv2.imshow("White",white) print(white[0,0,:]) # A blue images color = ones.copy() color[:,:] = (255,0,0) cv2.imshow("Blue",color) print(color[0,0,:]) cv2.waitKey(0) cv2.destroyAllWindows()
Extracting channels of images
import numpy as np import cv2 color = cv2.imread("butterfly.jpg", 1) cv2.imshow("Image",color) cv2.moveWindow("Image",0,0) print(color.shape) height,width,channels = color.shape b,g,r = cv2.split(color) rgb_split = np.empty([height,width*3,3],'uint8') rgb_split[:, 0:width] = cv2.merge([b,b,b]) rgb_split[:, width:width*2] = cv2.merge([g,g,g]) rgb_split[:, width*2:width*3] = cv2.merge([r,r,r]) cv2.imshow("Channels",rgb_split) cv2.moveWindow("Channels",0,height) hsv = cv2.cvtColor(color, cv2.COLOR_BGR2HSV) h,s,v = cv2.split(hsv) hsv_split = np.concatenate((h,s,v),axis=1) cv2.imshow("Split HSV",hsv_split) cv2.waitKey(0) cv2.destroyAllWindows()
Color Conversion RGB to GRAY
import numpy as np import cv2 color = cv2.imread("butterfly.jpg",1) gray = cv2.cvtColor(color, cv2.COLOR_RGB2GRAY) cv2.imwrite("gray.jpg",gray) b = color[:,:,0] g = color[:,:,1] r = color[:,:,2] rgba = cv2.merge((b,g,r,g)) cv2.imwrite("rgba.png",rgba)
blur, kernel, dilate and erode
import numpy as np import cv2 image = cv2.imread("thresh.jpg") cv2.imshow("Original",image) blur = cv2.GaussianBlur(image, (5,55),0) cv2.imshow("Blur",blur) kernel = np.ones((5,5),'uint8') dilate = cv2.dilate(image,kernel,iterations=1) erode = cv2.erode(image,kernel,iterations=1) cv2.imshow("Dilate",dilate) cv2.imshow("Erode",erode) cv2.waitKey(0) cv2.destroyAllWindows()
Resize and Rotate
import numpy as np import cv2 img = cv2.imread("players.jpg",1) # Scale img_half = cv2.resize(img, (0,0), fx=0.5, fy=0.5) img_stretch = cv2.resize(img, (600,600)) img_stretch_near = cv2.resize(img, (600,600), interpolation=cv2.INTER_NEAREST) cv2.imshow("Half",img_half) cv2.imshow("Stretch",img_stretch) cv2.imshow("Stretch near",img_stretch_near) # Rotation M = cv2.getRotationMatrix2D((0,0), -30, 1) rotated = cv2.warpAffine(img, M, (img.shape[1], img.shape[0])) cv2.imshow("Rotated",rotated) cv2.waitKey(0) cv2.destroyAllWindows()
Reading Videos:
import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() frame = cv2.resize(frame, (0,0), fx=0.5,fy=0.5) cv2.imshow("Frame",frame) ch = cv2.waitKey(1) if ch & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
Painting over video.
import numpy as np import cv2 cap = cv2.VideoCapture(0) color = (0,255,0) line_width = 3 radius = 100 point = (0,0) def click(event, x, y, flags, param): global point, pressed if event == cv2.EVENT_LBUTTONDOWN: print("Pressed",x,y) point = (x,y) cv2.namedWindow("Frame") cv2.setMouseCallback("Frame",click) while(True): ret, frame = cap.read() frame = cv2.resize(frame, (0,0), fx=0.5,fy=0.5) cv2.circle(frame, point, radius, color, line_width) cv2.imshow("Frame",frame) ch = cv2.waitKey(1) if ch & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
Object Detection.
Binary Threshold
import numpy as np import cv2 bw = cv2.imread('detect_blob.png', 0) height, width = bw.shape[0:2] cv2.imshow("Original BW",bw) binary = np.zeros([height,width,1],'uint8') thresh = 85 for row in range(0,height): for col in range(0, width): if bw[row][col]>thresh: binary[row][col]=255 cv2.imshow("Slow Binary",binary) ret, thresh = cv2.threshold(bw,thresh,255,cv2.THRESH_BINARY) cv2.imshow("CV Threshold",thresh) cv2.waitKey(0) cv2.destroyAllWindows()
Adaptive Threshold
import numpy as np import cv2 img = cv2.imread('sudoku.png',0) cv2.imshow("Original",img) ret, thresh_basic = cv2.threshold(img,70,255,cv2.THRESH_BINARY) cv2.imshow("Basic Binary",thresh_basic) thres_adapt = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) cv2.imshow("Adaptive Threshold",thres_adapt) cv2.waitKey(0) cv2.destroyAllWindows()
Operation on HSV and filters
import numpy as np import cv2 img = cv2.imread('faces.jpeg',1) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) h = hsv[:,:,0] s = hsv[:,:,1] v = hsv[:,:,2] hsv_split = np.concatenate((h,s,v), axis=1) cv2.imshow("Split HSV",hsv_split) ret, min_sat = cv2.threshold(s,40,255, cv2.THRESH_BINARY) cv2.imshow("Sat Filter",min_sat) ret, max_hue = cv2.threshold(h,15, 255, cv2.THRESH_BINARY_INV) cv2.imshow("Hue Filter",max_hue) final = cv2.bitwise_and(min_sat,max_hue) cv2.imshow("Final",final) cv2.imshow("Original",img) cv2.waitKey(0) cv2.destroyAllWindows()
Contours
import numpy as np import cv2 img = cv2.imread('detect_blob.png',1) # Convert gray gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Remove shadow thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) cv2.imshow("Binary", thresh) # Find cuntour _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) img2 = img.copy() index = -1 thickness = 4 color = (255, 0, 255) cv2.drawContours(img2, contours, index, color, thickness) cv2.imshow("Contours",img2) cv2.waitKey(0) cv2.destroyAllWindows()
contourArea, perimeter and centrold.
import numpy as np import cv2 img = cv2.imread('detect_blob.png',1) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) cv2.imshow("Binary", thresh) _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) img2 = img.copy() index = -1 thickness = 4 color = (255, 0, 255) objects = np.zeros([img.shape[0], img.shape[1],3], 'uint8') for c in contours: cv2.drawContours(objects, [c], -1, color, -1) area = cv2.contourArea(c) perimeter = cv2.arcLength(c, True) M = cv2.moments(c) cx = int( M['m10']/M['m00']) cy = int( M['m01']/M['m00']) cv2.circle(objects, (cx,cy), 4, (0,0,255), -1) print("Area: {}, perimeter: {}".format(area,perimeter)) cv2.imshow("Contours",objects) cv2.waitKey(0) cv2.destroyAllWindows()
Canny Edges detction:
import numpy as np import cv2 img = cv2.imread("tomatoes.jpg",1) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) res,thresh = cv2.threshold(hsv[:,:,0], 25, 255, cv2.THRESH_BINARY_INV) cv2.imshow("Thresh",thresh) edges = cv2.Canny(img, 100, 70) cv2.imshow("Canny",edges) cv2.waitKey(0) cv2.destroyAllWindows()
Object detction Models
matchTemplate to detcet objects
import numpy as np import cv2 template = cv2.imread('template.jpg',0) frame = cv2.imread("players.jpg",0) cv2.imshow("Frame",frame) cv2.imshow("Template",template) ## We just swep over the whole image to find the matchs. result = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) print(max_val,max_loc) cv2.circle(result,max_loc, 15,255,2) cv2.imshow("Matching",result) cv2.waitKey(0) cv2.destroyAllWindows()
Detection of face using haarcascade_frontalface
import numpy as np import cv2 img = cv2.imread("faces.jpeg",1) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) path = "haarcascade_frontalface_default.xml" face_cascade = cv2.CascadeClassifier(path) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.10, minNeighbors=5, minSize=(40,40)) print(len(faces)) for (x, y, w, h) in faces: cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2) cv2.imshow("Image",img) cv2.waitKey(0) cv2.destroyAllWindows()
Detection of eye using haarcascade_eye
import numpy as np import cv2 img = cv2.imread("faces.jpeg",1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) path = "haarcascade_eye.xml" eye_cascade = cv2.CascadeClassifier(path) eyes = eye_cascade.detectMultiScale(gray, scaleFactor=1.02,minNeighbors=20,minSize=(10,10)) print(len(eyes)) for (x, y, w, h) in eyes: xc = (x + x+w)/2 yc = (y + y+h)/2 radius = w/2 cv2.circle(img, (int(xc),int(yc)), int(radius), (255,0,0), 2) cv2.imshow("Eyes",img) cv2.waitKey(0) cv2.destroyAllWindows()
Computer Vision Projects