CV基础入门

1、读取图片

#导入模块
import cv2 as cv
#读取图片
img=cv.imread('lena.jpg') #路径中不能有中文,否则加载图片失败
#显示图片
cv.imshow('read_img',img)
#等待键盘输入 单位毫秒  传入0 则就是无限等待
cv.waitKey(3000)
#释放内存  由于OpenCV底层是C++编写的
cv.destroyAllWindows()

2、灰度转化

import cv2 as cv
img=cv.imread('lena.jpg')
cv.imshow('BGR_img',img)

#将图片灰度转换
gray_img=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow('gray_img',gray_img)
#保存图片
cv.imwrite('gray_lena.jpg',gray_img)
cv.waitKey(0)
cv.destroyAllWindows()

3、修改图片尺寸

pyimport cv2 as cv
img=cv.imread('lena.jpg')
cv.imshow('img',img)
print('原来图片的形状',img.shape)
# resize_img=cv.resize(img,dsize=(200,240))
resize_img=cv.resize(img,dsize=(600,560))
print('修改后图片的形状:',resize_img.shape)
cv.imshow('resize_img',resize_img)

# cv.waitKey(0)
#只有输入q时候,退出
while True:
    if ord('q')==cv.waitKey(0):
        break

cv.destroyAllWindows()

4、绘制选取框——矩形、圆

import cv2 as cv
img=cv.imread('lena.jpg')
#左上角的坐标是(x,y) 矩形的宽度和高度(w,h)
x,y,w,h=100,100,100,100
cv.rectangle(img,(x,y,x+w,y+h),color=(0,255,255),thickness=3) #BGR
#绘制圆center元组指圆点的坐标  radius:半径
x,y,r=200,200,100
cv.circle(img,center=(x,y),radius=r,color=(0,0,255),thickness=2)
#显示图片
cv.imshow('rectangle_img',img)
cv.waitKey(0)
cv.destroyAllWindows()

5、检测图片中的人脸

import cv2 as cv
def face_detect_demo():
    #将图片灰度
    gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    #加载特征数据
    face_detector = cv.CascadeClassifier(
        'E:/code_set/face_demo/facecode/haarcascade_frontalface_default.xml')
    faces = face_detector.detectMultiScale(gray)
    # 绘制选取框
    for x,y,w,h in faces:
        print(x,y,w,h)
        cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
        cv.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=2)
    #显示图片
    cv.imshow('result',img)

#加载图片
img=cv.imread('face3.jpg')
#调用人脸检测方法
face_detect_demo()
cv.waitKey(0)
cv.destroyAllWindows()

6、检测视频中的人脸

pyimport cv2 as cv
def face_detect_demo(img):
    #将图片灰度
    gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    #加载特征数据
    face_detector = cv.CascadeClassifier(
        'E:/soft/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
    faces = face_detector.detectMultiScale(gray)
    for x,y,w,h in faces:
        cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
        cv.circle(img,center=(x+w//2,y+h//2),radius=(w//2),color=(0,255,0),thickness=2)
    cv.imshow('result',img)

#读取视频
cap = cv.VideoCapture('video.mp4')
while True:
    flag,frame=cap.read()
    print('flag:',flag,'frame.shape:',frame.shape)
    if not flag:
        break
    face_detect_demo(frame)
    if ord('q') == cv.waitKey(10):
        break
cv.destroyAllWindows()
cap.release()

7、训练数据

import os
import cv2
import sys
from PIL import Image
import numpy as np
def getImageAndLabels(path):
    facesSamples=[]
    ids=[]
    imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
    #检测人脸
    face_detector = cv2.CascadeClassifier(
        'E:/code_set/face_demo/facecode/haarcascade_frontalface_default.xml')

    #遍历列表中的图片
    for imagePath in imagePaths:
        #打开图片
        PIL_img=Image.open(imagePath).convert('L')
        #将图像转换为数组
        img_numpy=np.array(PIL_img,'uint8')
        faces = face_detector.detectMultiScale(img_numpy)
        #获取每张图片的id
        id=int(os.path.split(imagePath)[1].split('.')[0])
        for x,y,w,h in faces:
            facesSamples.append(img_numpy[y:y+h,x:x+w])
            ids.append(id)
    return facesSamples,ids

if __name__ == '__main__':
    #图片路径
    path='./data/jm/'
    #获取图像数组和id标签数组
    faces,ids = getImageAndLabels(path)
    #获取训练对象
    recognizer=cv2.face.LBPHFaceRecognizer_create()
    recognizer.train(faces,np.array(ids))
    #保存文件
    recognizer.write('trainer/trainer.yml')

8、人脸识别

import cv2
import numpy as np
import os

#加载训练数据集文件
recogizer=cv2.face.LBPHFaceRecognizer_create()
recogizer.read('trainer/trainer.yml')

#准备识别的图片
img=cv2.imread('30.jpg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

face_detector = cv2.CascadeClassifier(
    'E:/code_set/face_demo/facecode/haarcascade_frontalface_default.xml')
faces = face_detector.detectMultiScale(gray)

for x,y,w,h in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

    #人脸识别
    id,confidence=recogizer.predict(gray[y:y+h,x:x+w])
    print('标签id:',id,'置信评分:',confidence)

cv2.imshow('result',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

文章作者: 寜笙
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 寜笙 !
 上一篇
2022-05-31 寜笙
下一篇 
2022-05-07 寜笙
  目录