OpenCV needs Python 2.7
Basic GUI
import cv2 as cvimport numpy as np
load image (wrong path do not throw error), show image, write image
img = cv.read('test.jpg', -1) # -1 color, 0 gray, 1 including alphacv.show('title', img)cv.waitKey(0) # wait for keyboard interrupt in millisec, 0 forevercv.destroyAllWindows() # close imagecv.imwrite('image_name.jpg', img)
little tip for key interrupt
k = cv.waitKey(0)if k == 27: # wait for ESC key to exit cv.destroyAllWindows()elif k == ord('s'): # wait for 's' key to save and exit cv.imwrite('messigray.png',img) cv.destroyAllWindows()
capture the video, convert to gray and play
cap = cv.VideoCapture(0)while(True): ret, frame = cap.read() gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) cv.imshow('frame',gray) if cv.waitKey(1) & 0xFF == ord('q'): breakcap.release()cv.destroyAllWindows()
draw
# Create a black imageimg = np.zeros((512,512,3), np.uint8)# blue line with thickness of 5 pxcv.line(img,(0,0),(511,511),(255,0,0),5)# rectangle (top-left, bottom right)cv.rectangle(img,(384,0),(510,128),(0,255,0),3)# circle (center, radius)cv.circle(img,(447,63), 63, (0,0,255), -1)cv.circle(img,(447,63), 63, (0,0,255), -1)# add text to the imagefont = cv.FONT_HERSHEY_SIMPLEXcv.putText(img,'title',(10,500), font, 4,(255,255,255),2,cv.LINE_AA)# title, font, size, color, thickness, linetype
mouse event, use following code to show available events
import cv2 as cvevents = [i for i in dir(cv) if 'EVENT' in i]print( events )
example, when double click, draw a circle
# mouse callback functiondef draw_circle(event,x,y,flags,param): if event == cv.EVENT_LBUTTONDBLCLK: cv.circle(img,(x,y),100,(255,0,0),-1) # Create a black image, a window and bind the function to windowimg = np.zeros((512,512,3), np.uint8)cv.namedWindow('image')cv.setMouseCallback('image',draw_circle)while(1): cv.imshow('image',img) if cv.waitKey(20) & 0xFF == 27: breakcv.destroyAllWindows()
Image Process
access pixel
px = img[100,100] # pixel positionprint ( px ) # result is [b,g,r]blue = img[100,100,0] # access blue channelimg[100,100] = [0,0,0] # change it to black# for individual pixel, following is fasterpx = img.item(100,100,0)
use img.shape,img.size,img.dtype
to see image properties
select a region
ball = img[280:340, 330:390]
channel split and merge
b,g,r = cv.split(img)img = cv.merge((b,g,r))
add
cv.add(img1,img2)cv.addWeighted(img1,0.7, img2,0.3, 0) # w1, w2, b
also bitwise operations omitted here
Measurement
can use following code, can also use time.time()
e1 = cv.getTickCount()e2 = cv.getTickCount()t = (e2 - e1)/cv.getTickFrequency()print (t)