ComputerGraphicsNotesWeek9 01 0418
ComputerGraphicsNotesWeek9 01 0418
ComputerGraphicsNotesWeek9-01-
0418
1.1. install opencv
pip install opencv-python
Review materials:
opencv24-python-tutorials-readthedocs-io-en-stable.pdf
A patch is a small image with certain features. The goal of template matching is to find the
patch/template in an image.
Example:
import cv2
import numpy as np
img = cv2.imread('mainimage.jpg', 0)
img2 = img.copy()
template = cv2.imread('template.jpg', 0)
w, h = template.shape[::-1]
img = img2.copy()
method = eval(meth)
top_left = min_loc
else:
top_left = max_loc
plt.show()
import numpy as np
img = cv2.imread('mainimage.jpg',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,200,
param1=50,param2=30,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
img = cv2.imread('mainimage.jpg')
mask = np.zeros(img.shape[:2],np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (50,0,450,500)
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]
plt.imshow(img),plt.colorbar(),plt.show()
import cv2
def videocapture():
cap=cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
writer = cv2.VideoWriter("video_result.mp4", fourcc, fps, (width, height))
while cap.isOpened():
ret, frame = cap.read()
cv2.imshow('teswell', frame)
key = cv2.waitKey(24)
writer.write(frame)
#press q to quit
if key == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if name == 'main' :
videocapture()
1.7. Homework
write a program to open camera and save it to video file if you have a camera, if not, just write a
program to open a video file and save it as jpg or another video file with different file names,