赞
踩
# 导入cv模块
import cv2 as cv
# 读取图片
img = cv.imread('XZQ.jpg')
# 显示照片
cv.imshow('read_img', img)
# 等待
cv.waitKey(0)
# 释放内存
cv.destroyAllWindows()
# 导入cv模块 import cv2 as cv # 读取图片 img = cv.imread('XZQ.jpg') # 灰度转换 gray_img = cv.cvtColor(img, cv.COLOR_RGB2GRAY) # 显示灰度 cv.imshow('gray', gray_img) # 保存灰度照片 cv.imwrite('grat_XZQ.jpg', gray_img) # 显示照片 cv.imshow('read_img', img) # 等待 cv.waitKey(0) # 释放内存 cv.destroyAllWindows()
# 导入cv模块 import cv2 as cv # 读取图片 img = cv.imread('XZQ.jpg') # 修改尺寸 resize_img = cv.resize(img, dsize=(200, 200)) # 显示原图 cv.imshow('img', img) # 显示修改后的 cv.imshow('resize_img', resize_img) # 打印原图尺寸大侠 print('未修改:', img.shape) # 打印修改后的大小 print('修改后:', resize_img.shape) # 等待 while True: if ord('q') == cv.waitKey(0): break # 释放内存 cv.destroyAllWindows()
# 导入cv模块 import cv2 as cv # 读取图片 img = cv.imread('XZQ.jpg') # 坐标 x, y, w, h = 100, 100, 200, 200 # 绘制矩形 cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=1) # 绘制圆形 cv.circle(img, center=(x + w//2, y + h//2), radius=100, color=(255, 0, 0), thickness=2) # 显示 cv.imshow('re_img', img) # 等待 while True: if ord('q') == cv.waitKey(0): break # 释放内存 cv.destroyAllWindows()
# 导入cv模块 # 导入cv模块 import cv2 as cv def face_detect_demo(): gary = cv.cvtColor(img, cv.COLOR_BGR2GRAY) face_detect = cv.CascadeClassifier('D:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml') face = face_detect.detectMultiScale(gary, 1.01, 5, 0, (100, 100), (300, 300)) for x, y, w, h in face: cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 225), thickness=2) cv.imshow('result', img) # 读取图片 img = cv.imread('XZQ.jpg') # 检测函数 face_detect_demo() # 等待 while True: if ord('q') == cv.waitKey(0): break # 释放内存 cv.destroyAllWindows()
# 导入cv模块 import cv2 as cv def face_detect_demo(img): gary = cv.cvtColor(img, cv.COLOR_BGR2GRAY) face_detect = cv.CascadeClassifier('D:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml') face = face_detect.detectMultiScale(gary) for x, y, w, h in face: cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 225), thickness=2) cv.imshow('result', img) # 读取摄像头 cap = cv.VideoCapture('XZQTianWaiLaiWu.mp4') # 循环 while True: flag, frame = cap.read() if not flag: break # 修改尺寸 resize_img = cv.resize(frame, dsize=(700, 500)) face_detect_demo(resize_img) if ord('q') == cv.waitKey(1): break # 释放内存 cv.destroyAllWindows() # 释放摄像头 cap.release()
# 导入模块 import cv2 cap = cv2.VideoCapture('XZQTianWaiLaiWu.mp4') num = 1 while (cap.isOpened()): # 检测是否在开启状态 ret_flag, Vshow = cap.read() # 得到每帧图像 cv2.imshow("Capture_Test", Vshow) # 显示图像 k = cv2.waitKey(1) & 0xFF # 按键判断 if k == ord('s'): # 保存 cv2.imwrite("data/" + str(num) + ".name" + ".jpg", Vshow) print('success to sava' + str(num) + '.jpg') print('----------------------') num += 1 elif k == ord(' '): # 推出 break # 释放摄像头 cap.release() # 释放内存 cv2.destroyAllWindows()
import os import cv2 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('D:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml') # 便利列表中的图片 for imagePath in imagePaths: # 打开图片,灰度化 PIL 有九种不同模式:1,L,P,RGB,RGBA,CMYK,YCbCr,I,F 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: ids.append(id) facesSamples.append(img_numpy[y:y + h, x:x + w]) # 打印面部特征和id print('id:', id) print('fs:', facesSamples) return facesSamples, ids if __name__ == '__main__': # 图片路径 path = 'data/' # 获取图像数组和id标签数组和姓名 faces, ids = getImageAndLabels(path) # 加载识别器 recognizer = cv2.face.LBPHFaceRecognizer_create() # 训练 recognizer.train(faces, np.array(ids)) # 保存文件 recognizer.write('trainer/trainer.yml')
import cv import cv2 import os import urllib import urllib.request import numpy from PIL import Image, ImageDraw, ImageFont # 加载训练用数据文件 recogizer = cv2.face.LBPHFaceRecognizer_create() # 加载数据 recogizer.read('trainer/trainer.yml') # 名称 names = ['薛之谦']*10 # 警报全局变量 warningtime = 0 # md5加密 def md5(str): import hashlib m = hashlib.md5() m.update(str.encode('utf8')) return m.hexdigest() # 短信反馈 statuStr = { '0': '短信发送成功', '-1': '参数不全', '-2': '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间', '30': '密码错误', '40': '账号不存在', '41': '余额不足', '42': '账户已过期', '43': 'IP地址限制', '50': '内容含有敏感词' } # 报警模块 def warning(): print('陌生人') # 下面注释的是一种短信警告方式 ''' smsapi = 'http://api.smsbao.com/' #短信平台账号 user = '176****9967' #短信平台密码 password = md5('*********') # 要发送的短信内容 content = '【警报】 \n原因:xxx\n地点:xxx\n时间:xxx' # 要发送短信的手机号码 phone = '176****9967' data = urllib.parse.urlencode({'u':user,'p':password,'m':phone,'c':content}) send_url = smsapi + 'sms?' + data response = urllib.request.urlopen(send_url) the_page = response.read().decode('utf-8') print(statuStr[the_page]) ''' # 转中文 def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20): if (isinstance(img, numpy.ndarray)): # 判断是否OpenCV图片类型 img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # 创建一个可以在给定图像上绘图的对象 draw = ImageDraw.Draw(img) # 字体的格式 fontStyle = ImageFont.truetype("font/simsun.ttc", textSize, encoding="utf-8") # 绘制文本 draw.text((left, top), text, textColor, font=fontStyle) # 转换回OpenCV格式 return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR) # 准备识别的图片 def face_detect_demo(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换为灰度 # 加载数据库 face_detector = cv2.CascadeClassifier('D:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml') # 从数据库查询 # face = face_detector.detectMultiScale(gray, 1.1, 5, cv2.CASCADE_SCALE_IMAGE, (100, 100), (300, 300)) face = face_detector.detectMultiScale(gray) for x, y, w, h in face: cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=1) cv2.circle(img, center=(x + w // 2, y + h // 2), radius=w // 2, color=(0, 255, 0), thickness=1) # 人脸识别 ids, confidence = recogizer.predict(gray[y:y + h, x:x + w]) # print('标签id:',ids,'置信评分:',confidence) if confidence > 80: global warningtime warningtime += 1 if warningtime > 100: warning() warningtime = 0 cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1) else: # cv2.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1) # cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20) img = cv2ImgAddText(img, names[ids - 1], x + 10, y - 20) print('薛之谦!!') cv2.imshow('result', img) # print('bug:',ids) if __name__ == '__main__': # 读取摄像头 cap = cv2.VideoCapture('XZQTianWaiLaiWu.mp4') # 视频来源 # 循环 while True: flag, frame = cap.read() if not flag: break resize_img = cv2.resize(frame, dsize=(700, 500)) face_detect_demo(resize_img) if ord('q') == cv2.waitKey(1): break # 释放内存 cv2.destroyAllWindows() # 释放摄像头 cap.release()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。