#计算机视觉1 openCV+python的基本运用

识别图片中人脸

  • 改变文件地址(文件地址最好不要有中文)
import cv2
import os
import matplotlib.pyplot as plt
os.chdir('D:\Python 32\Lib\site-packages\cv2\data')
print(os.getcwd())
  • 此处更改的是py文件的地址,图片需要关联到相关data地址下,为今后方便再data下建立img文件夹
def detect(filename):
    face_cascade = cv2.CascadeClassifier('D:\Python 32\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')

    img = cv2.imread(filename)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
            img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
    plt.imshow(img)
    plt.axis('off')  #去掉坐标轴
    plt.show()
  • 运行函数
detect("img\old.jpg")

其他openCV文件的作用(data文件夹下)

openCV图像处理

import cv2
# 读取图像
im = cv2.imread('picpath')
h,w = im.shape[:2]
print h,w
# 保存图像
cv2.imwrite('result.png',im)

im = cv2.imread('empire.jpg')
# 创建灰度图像
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

#在读取原图像之后,紧接其后的是 OpenCV 颜色转换代码,其中最有用的一些转换
#代码如下:cv2.COLOR_BGR2GRAY(灰度图) /cv2.COLOR_BGR2RGB /cv2.COLOR_GRAY2BGR

openCV视频处理

import cv2
cap = cv2.VideoCapture('footage.mp4')

while True:
    ret, frame = cap.read()
    if frame is None:
        break

    img_gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
    img_blurred = cv2.GaussianBlur(img_gray, (5, 5), 0)
    img_threshold1 = cv2.adaptiveThreshold(img_blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 2)
    img_threshold1_blurred = cv2.GaussianBlur(img_threshold1, (5, 5), 0)
    _, img_threshold2 = cv2.threshold(img_threshold1_blurred, 200, 255, cv2.THRESH_BINARY)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3))
    img_opening = cv2.bitwise_not(cv2.morphologyEx(cv2.bitwise_not(img_threshold2), cv2.MORPH_OPEN, kernel))
    img_opening_blurred = cv2.GaussianBlur(img_opening, (3, 3), 0)
    cv2.imshow('img_opening_blurred', img_opening_blurred)

    if cv2.waitKey(40) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()
import numpy as np
import cv2 as cv

cap = cv.VideoCapture('vtest.avi')
while cap.isOpened():
    ret, frame = cap.read()

    # if frame is read correctly ret is True
    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()

https://zhuanlan.zhihu.com/p/62703610
知乎openCV专栏: https://www.zhihu.com/topic/19587715/hot

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值