1.图像处理:读取图像,显示图像,保存图像
import cv2 as cv
# Loads a color image. Any transparency of image will be neglected.
img1 = cv.imread('Lenna.png', cv.IMREAD_COLOR) # Color image loaded by OpenCV is in BGR mode.
# Loads image in grayscale mode
img2 = cv.imread('Lenna.png', cv.IMREAD_GRAYSCALE)
# Loads image as such including alpha channel
img3 = cv.imread('Lenna.png', cv.IMREAD_UNCHANGED)
# cv.WINDOW_NORMAL means that you can resize window.
cv.namedWindow('img1', cv.WINDOW_NORMAL)
cv.imshow('img1', img1)
cv.namedWindow('img2', cv.WINDOW_NORMAL)
cv.imshow('img2', img2)
cv.namedWindow('img3', cv.WINDOW_NORMAL)
cv.imshow('img3', img3)
# cv.IMREAD_COLOR is the default flag,so you can omit this flag
img = cv.imread('Lenna.png')
# cv.WINDOW_AUTOSIZE means that the window automatically fits to the image size.
cv.namedWindow('img', cv.WINDOW_AUTOSIZE)
cv.imshow('img', img)
cv.imwrite('Lenna_copy.png', img)
cv.waitKey(0) # It waits indefinitely for a key stroke
cv.destroyWindow('img') # destroy specific window
cv.destroyAllWindows() # destroys all the windows we created
2.waitKey()的用法
import cv2 as cv
img = cv.imread("Lenna.png")
cv.imshow("image", img)
k = cv.waitKey(0) & 0xFF # "& 0xFF" is necessary for 64-bit machine
if k == 27: # wait for ESC key to exit(ESC ASCII code:27)
cv.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv.imwrite('Lenna_copy.png', img)
cv.destroyAllWindows()
3.视频处理:读取摄像头视频流中的图像帧
import cv2 as cv
cap = cv.VideoCapture(0) # 0 represents webcam
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
4.视频处理:读取视频文件中的图像帧
import cv2 as cv
cap = cv.VideoCapture("lee.mp4") # video file
# Define the codec and create VideoWriter object
fourcc = cv.VideoWriter_fourcc(*'DIVX')
out = cv.VideoWriter('test.avi', fourcc, 20, (544, 960))
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# print(cap.get(cv.CAP_PROP_FRAME_WIDTH), cap.get(cv.CAP_PROP_FRAME_HEIGHT))
# print(cap.set(cv.CAP_PROP_FRAME_WIDTH, 400), cap.set(cv.CAP_PROP_FRAME_HEIGHT, 300))
# if frame is read correctly, ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# frame = cv.flip(frame, 0) # flip every frame in vertical direction
# frame = cv.flip(frame, 1) # flip every frame in horizontal direction
out.write(frame)
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
cv.imshow("image", gray)
if cv.waitKey(1) == ord('q'):
break
# When everything done, release the capture
cap.release()
out.release()
cv.destroyAllWindows()
5.使用matplotlib绘图
import cv2
from matplotlib import pyplot as plt
img1 = cv2.imread('Lenna.png')
b, g, r = cv2.split(img1)
img2 = cv2.merge([r, g, b])
cv2.imshow('bgr image', img1) # expects true color
cv2.imshow('rgb image', img2) # expects distorted color
# Matplotlib displays image in RGB mode!!!
plt.subplot(121)
plt.imshow(img1) # expects distorted color
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.subplot(122)
plt.imshow(img2) # expect true color
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
6.绘制图形和添加文字
import cv2 as cv
import numpy as np
# Create a black image
img = np.zeros((512, 512, 3), np.uint8)
# Draw a diagonal blue line with thickness of 5 px
cv.line(img, (0, 0), (511, 511), (255, 0, 0), 5)
cv.rectangle(img,
(384, 0), # coordinate of rectangle's upper left point
(510, 128), # coordinate of rectangle's lower right point
(0, 255, 0), # color of rectangle's edges
3) # thickness of rectangle's edges
cv.circle(img,
(447, 63), # coordinate of circle
63, # radius of circle
(0, 0, 255), # color of circumference
-1) # thickness of circumference
cv.ellipse(img,
(256, 256), # center
(100, 50), # axis
0, # angle
0, # startAngle
180, # endAngle
255, # color of circumference
-1) # thickness of circumference
# Drawing Polygon
pts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv.polylines(img, [pts], True, (0, 255, 255))
font = cv.FONT_HERSHEY_SIMPLEX
cv.putText(img, 'OpenCV',
(10, 500), # position of text
font,
4, # fontScale
(255, 255, 255), # text color
2, # text thickness
cv.LINE_AA) # line style
cv.imshow("image", img)
cv.waitKey(0)
cv.destroyAllWindows()
7.鼠标点击事件
- 查看opencv中定义的鼠标点击事件
import cv2 as cv
events = [i for i in dir(cv) if 'EVENT' in i]
print( events )
['EVENT_FLAG_ALTKEY', 'EVENT_FLAG_CTRLKEY', 'EVENT_FLAG_LBUTTON', 'EVENT_FLAG_MBUTTON', 'EVENT_FLAG_RBUTTON', 'EVENT_FLAG_SHIFTKEY', 'EVENT_LBUTTONDBLCLK', 'EVENT_LBUTTONDOWN', 'EVENT_LBUTTONUP', 'EVENT_MBUTTONDBLCLK', 'EVENT_MBUTTONDOWN', 'EVENT_MBUTTONUP', 'EVENT_MOUSEHWHEEL', 'EVENT_MOUSEMOVE', 'EVENT_MOUSEWHEEL', 'EVENT_RBUTTONDBLCLK', 'EVENT_RBUTTONDOWN', 'EVENT_RBUTTONUP']
import numpy as np
import cv2 as cv
# mouse callback function
def 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 window
img = np.zeros((512, 512, 3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image', draw_circle)
while True:
cv.imshow('image', img)
if cv.waitKey(20) & 0xFF == 27:
break
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press 'm' to toggle to curve
ix, iy = -1, -1
# mouse callback function
def draw_circle(event, x, y, flags, param):
global ix, iy, drawing, mode
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv.EVENT_MOUSEMOVE:
if drawing == True:
if mode == True:
cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)
else:
cv.circle(img, (x, y), 5, (0, 0, 255), -1)
elif event == cv.EVENT_LBUTTONUP:
drawing = False
if mode == True:
cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)
else:
cv.circle(img, (x, y), 5, (0, 0, 255), -1)
img = np.zeros((512, 512, 3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image', draw_circle)
while True:
cv.imshow('image', img)
k = cv.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break
cv.destroyAllWindows()
8.计算程序运行时间
import cv2 as cv
e1 = cv.getTickCount()
# your code execution
e2 = cv.getTickCount()
time = (e2 - e1) / cv.getTickFrequency()