Opencv-python4.5学习笔记

Opencv-python4.5学习笔记

    • 读取、展示、保存图片
    • 摄像头读取视频并转为灰度图显示
    • 播放视频文件
    • 从摄像头读取帧保存视频
    • 画图、显示文字
    • 鼠标响应
    • 滑动轨迹条
    • 像素、分离RGB通道
    • ROI
    • 图像运算
    • 计算时间
    • 颜色空间转换
    • 根据HSV颜色追踪物体

读取、展示、保存图片

import cv2 as cv
import sys

img = cv.imread("ying.jpg")
if img is None:
    sys.exit("Could not read the image.")
cv.imshow("Display window",img)
k = cv.waitKey(0)
if k == ord("s"):
    cv.imwrite("ying.png",img)

摄像头读取视频并转为灰度图显示

import cv2 as cv
import sys
import numpy as np

cap = cv.VideoCapture(0)
print(cap.get(cv.CAP_PROP_FRAME_WIDTH))  #640.0
print(cap.get(cv.CAP_PROP_FRAME_HEIGHT)) #480.0
cap.set(cv.CAP_PROP_FRAME_WIDTH,320)
cap.set(cv.CAP_PROP_FRAME_HEIGHT,240)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    ret,frame = cap.read() #成功读取数据返回ret=True,else ret = False

    if not ret:
        print("Can't receive frame (stream end?).Exitint...")
        break

    gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY) 
    #cvtColor,转换显示颜色,BGR2GRAY:BGR转为灰度
    cv.imshow("frame",gray)
    if cv.waitKey(1) == ord('q'):
        break

cap.release()
cv.destroyAllWindows()

播放视频文件

import numpy as np
import cv2 as cv

cap = cv.VideoCapture('vtest.avi')
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
cap.release()
cv.destroyAllWindows()

从摄像头读取帧保存视频

import cv2 as cv
import time
cap = cv.VideoCapture(0)
#fourcc是用于表示视频信息的四字节编码
fourcc = cv.VideoWriter_fourcc('M','J','P','G')
out = cv.VideoWriter('test.avi',fourcc,30,(640,480),1)
#保存的文件名,编码类型,fps(帧/秒),大小,色彩(0表示灰度,其他表示彩色)
if not cap.isOpened():
    raise Exception("Cannot open camera")

t0 = time.time()  #用来保存一段时间长度的视频
while True:
    ret,frame = cap.read()
    if not ret:
        print("Can't receive frame (stream end?).Exitint...")
        break
    frame = cv.flip(frame,1) #左右翻转
    out.write(frame)
    cv.imshow("frame",frame)
    t = time.time() - t0
    if t >= 30:
        break
    if cv.waitKey(1) == ord('q'):
        break

cap.release()
cv.destroyAllWindows()

画图、显示文字

img = cv.imread('ying.jpg')
cv.line(img,(0,0),(800,800),(0,255,0),5)
#(0,0)线条起点,(800,800)终点,(0,255,0)绿色,厚度5
#矩形
cv.rectangle(img,(400,400),(500,500),(255,0,0),5)
#圆
cv.circle(img,(550,700),50,(0,0,255),1)
#(550,700)圆心,50半径,1表示不填充,只显示线条,-1表示填充整个区域
#椭圆
cv.ellipse(img,(256,256),(100,50),0,0,360,(0,255,0),-1)
#(256,256)中心,(100,50)即(a,b),0,0,两个0为旋转角度,360即显示的区域大小,(0,255,0),-1同上
#多边形
pts = np.array([[100,100],[200,200],[100,200],[200,100],[300,300]], np.int32)
pts = pts.reshape((-1,1,2))
cv.polylines(img,[pts],True,(0,255,255))
#在图像显示文字
font = cv.FONT_HERSHEY_SIMPLEX
cv.putText(img,'come on baby',(10,500), font, 4,(255,255,255),2,cv.LINE_AA)

cv.imshow("ying",img)
cv.waitKey(0)
cv.destroyAllWindows()

鼠标响应

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']

drawing = False
mode = True
ix,iy = -1,-1

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 = cv.imread('ying.png')
cv.namedWindow('ying')
cv.setMouseCallback('ying',draw_circle)

while True:
    cv.imshow('ying',img)
    k = cv.waitKey(20) & 0xFF
    if k == 27:
        break
    elif k == ord('m'):
        mode = not mode
cv.destroyAllWindows()

效果:按下鼠标,该位置为起点,按住鼠标移动,会根据当前鼠标位置和起点画图,按下m切换画图方式。

滑动轨迹条

def nothing(x):
    pass
# Create a black image, a window
img = np.zeros((300,512,3), np.uint8)
cv.namedWindow('image')
# create trackbars for color change
cv.createTrackbar('R','image',0,255,nothing)
cv.createTrackbar('G','image',0,255,nothing)
cv.createTrackbar('B','image',0,255,nothing)
# create switch for ON/OFF functionality
switch = '0 : OFF \n1 : ON'
cv.createTrackbar(switch, 'image',0,1,nothing)
while(1):
    cv.imshow('image',img)
    k = cv.waitKey(1) & 0xFF
    if k == 27:
        break
    # get current positions of four trackbars
    r = cv.getTrackbarPos('R','image')
    g = cv.getTrackbarPos('G','image')
    b = cv.getTrackbarPos('B','image')
    s = cv.getTrackbarPos(switch,'image')
    if s == 0:
        img[:] = 0
    else:
        img[:] = [b,g,r]
cv.destroyAllWindows()

像素、分离RGB通道

opencv读取的每一帧图像的类型是[width,height,channels],其中channels即图像的通道数,对于RGB真彩型图像来说,最后一维即R、G、B三个像素。

#分离ROI的RGB三通道参数并取平均值
B = np.average(roi[:,:,0])
G = np.average(roi[:,:, 1])
R = np.average(roi[:,:, 2])

ROI

处理图像通常需要截取其中某部分我们感兴趣的区域,即ROI。截取方式有很多。

#在frame中按比例截取ROI
roi = frame[int(y + 0.1 * h):int(y + 0.25 * h),int(x + 0.3 * w):int(x + 0.7 * w)]

注意:通过固定比例截取的ROI区域,随着镜头移动,区域会改变,影响后续实验结果。

图像运算

cv.add(x,y)
x,y图像大小和类型要相同,若某个点像素相加超过255,只会取255.

cv.addWeighted(img1,0.7,img2,0.3,0)
图像按权重相加,dst=α⋅img1+β⋅img2+γ

计算时间

e1 = cv.getTickCount()
#代码执行
e2 = cv.getTickCount()
time = (e2 - e1)/ cv.getTickFrequency()

类似于Python中的:

import time
t0 = time.time()
#执行代码
t = time.time() - t0

颜色空间转换

gray = cv.cvtColor(flame,cv.COLOR_BGR2GRAY)
hsv = cv.cvtColor(flame,cv.COLOR_BGR2HSV)

灰度图的通道只有一个,hsv空间有Hue、Saturation、Value.

根据HSV颜色追踪物体

import cv2 as cv
import numpy as np
cap = cv.VideoCapture(0)
while(1):
    # Take each frame
    _, frame = cap.read()
    # Convert BGR to HSV
    hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])
    # Threshold the HSV image to get only blue colors
    mask = cv.inRange(hsv, lower_blue, upper_blue)
    # Bitwise-AND mask and original image
    res = cv.bitwise_and(frame,frame, mask= mask)
    cv.imshow('frame',frame)
    cv.imshow('mask',mask)
    cv.imshow('res',res)
    k = cv.waitKey(5) & 0xFF
    if k == 27:
        break
cv.destroyAllWindows()

SURF特征提取

import cv2 as cv

img = cv.imread('ying.png',0)
#创建SURF对象
surf = cv.xfeatures2d.SURF_create(400) #400为初始阈值
#设置阈值
surf.setHessianThreshold(10000)
kp,des = surf.detectAndCompute(img,None)
#特征点数量
print(len(kp))
#显示特征点
img2 = cv.drawKeypoints(img,kp,None,(255,0,0),2)
cv.imshow("keypoints",img2)
cv.waitKey(0)

你可能感兴趣的:(AI常用库,opencv)