import requests
# 授权服务地址
auth_url = "https://openapi.baidu.com/oauth/2.0/token"
# API Key和Secret Key
api_key = "ZeU0lSVXkcnxpDznPom9wLed"
secret_key = "YjLGJbpyoHiVkVIxJiAIRoxP9lR4E9dG"
# 请求参数
params = {
"grant_type": "client_credentials",
"client_id": api_key,
"client_secret": secret_key,
}
# 发起请求
response = requests.get(auth_url, params=params)
# 打印响应信息
print(response.json())
import base64
import urllib
import requests
import json
def main():
url = "https://vop.baidu.com/server_api"
speech = get_file_content_as_base64(r"C:\Users\24106\Desktop\01\01_1\voice.wav",False)
payload = json.dumps({
"format": "wav",
"rate": 16000,
"channel": 1,
"cuid": "qlTsAe1gh4zDm6YmlT2dKFNcZNwesrOj",
"token": "24.cb51abdf527ef5f48153076d0900f248.2592000.1714194185.282335-58589834",
"speech": speech,
"len": 159942
})
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
def get_file_content_as_base64(path, urlencoded=False):
"""
获取文件base64编码
:param path: 文件路径
:param urlencoded: 是否对结果进行urlencoded
:return: base64编码信息
"""
with open(path, "rb") as f:
content = base64.b64encode(f.read()).decode("utf8")
if urlencoded:
content = urllib.parse.quote_plus(content)
return content
if __name__ == '__main__':
main()
import cv2
import pandas as pd
import numpy as np
from tensorflow.keras.models import load_model
# 加载人脸检测分类器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 加载口罩识别模型
model = load_model('mask_recog_ver2.h5')
# 打开摄像头
cap = cv2.VideoCapture(0)
# 创建空的DataFrame用于存储结果
results_list = []
frame_number = 0
while True:
# 读取摄像头帧
ret, frame = cap.read()
frame_number += 1
# 将帧转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame_color = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
# 检测人脸
faces = face_cascade.detectMultiScale(frame_color, 1.1, 4)
for (x, y, w, h) in faces:
# 提取人脸区域
face_roi = frame_color[y:y+h, x:x+w]
face_roi = cv2.resize(face_roi, (224, 224))
face_roi = np.expand_dims(face_roi, axis=0)
face_roi = face_roi / 255.0
# 预测口罩
prediction = model.predict(face_roi)
confidence0 = prediction[0][0]
confidence1 = prediction[0][1]
# 在帧上绘制矩形框和标签
color = (0, 255, 0) if confidence0 > 0.5 else (0, 0, 255)
label = f"Mask: {confidence0:.2f}" if confidence0 > 0.5 else f"No Mask: {confidence1:.2f}"
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(frame, label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
# 将结果添加到DataFrame中
results_list.append({'frame_number': frame_number, 'mask_confidence': confidence1})
for result in results_list:
print(result)
# 显示帧
cv2.imshow('Face Mask Detection', frame)
# 按下q键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头并销毁所有窗口
cap.release()
cv2.destroyAllWindows()
# 将DataFrame保存为excel文件
results_df = pd.DataFrame(results_list)
results_df.to_excel('mask_detection_results.xlsx', index=False)
# coding=gb2312
"""
@version: python3.6.9
@Author : xiaor
@Explain :配置文件
@contact :
@Time :2023/07/04
@File :xr_config.py
"""
from scservo_sdk import * # Uses SCServo SDK library
# Default setting
BAUDRATE = 500000 # SCServo default baudrate : 500000. 设置波特率
DEVICENAME = '/dev/ttyUSB0' # Check which port is being used on your controller. 选择串口
# ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"
# Initialize PortHandler instance
# Set the port path
# Get methods and members of PortHandlerLinux or PortHandlerWindows
portHandler = PortHandler(DEVICENAME)
# Initialize PacketHandler instance
# Get methods and members of Protocol
packetHandler = sms_sts(portHandler)
# Open port
if portHandler.openPort():
print("Succeeded to open the port")
else:
print("Failed to open the port")
quit()
# Set port baudrate
if portHandler.setBaudRate(BAUDRATE):
print("Succeeded to change the baudrate")
else:
print("Failed to change the baudrate")
quit()
# 云台舵机编号
SCS_ID_X = 11
SCS_ID_Y = 12
SCS_MOVING_SPEED = 1500 # SCServo moving speed 旋转速度
SCS_MOVING_ACC = 50 # SCServo moving acc 旋转加速度
def angle(value):
if value < -180:
value = -180
elif value > 180:
value = 180
angle = int(11.378 * float(value) )+ 2047
if angle < 0:
angle = 0
elif angle > 4095:
angle = 4095
return angle
'''
Time:2023.3.22
Company:小二极客科技有限公司
Use:Inverse kinematics algorithm for a three link manipulator(三连杆接机械臂逆运动学算法)
'''
import math
def calculate_angle():
pi = 3.14
# Define the length of each link
# 定义连杆长度,单位为毫米
L1 = 105 # L1
L2 = 100 # L2
L3 = 120 # L3
# Define the end-effector position and orientation
# 定义末端关节的位置为x,y,单位为毫米,姿态为theta(即 L3与X轴的夹角,这里设置为0 ),单位为弧度。这math.radians函数将角度转换为弧度
x = int(input("x:"))
y = int(input("y:"))
theta = math.radians(0)
# Calculate the intermediate position
# 计算中间位置Bx,By,即第二个关节的位置。这里用三角函数和末端关节的位置和姿态来求解
Bx = x - L3 * math.cos(theta)
By = y - L3 * math.sin(theta)
# Calculate the first and second joint angles using inverse kinematics formula for two-link arm
# 计算第一个和第二个关节的角度q1,q2,使用二连杆机械臂的逆运动学公式。
# 这里用math.acos和math.atan2函数来求解反余弦和反正切。使用math.sqrt函数求平方根
lp = Bx**2 + By**2
alpha = math.atan2(By, Bx)
beta = math.acos((L1*L1 + lp - L2*L2) / (2*L1*math.sqrt(lp)))
q1 = -(pi/2.0 - alpha - beta)
q2 = math.acos((L1*L1 + L2*L2 - lp) / (2*L1*L2)) - pi
# Calculate the third joint angle using the end-effector orientation
# 计算第三个关节的角度q3,使用末端关节的姿态(预先定义,theta)减去前两个角度得到。
# math.degrees函数将弧度转换为角度
q3 = - q1 - q2 - pi/2
# 舵机编号3、4、5控制伸缩姿态,每一个舵机的初始值为2047,与前一个连杆处于同一直线。每一个舵机的取值范围:0~4095,相当于0~360度
# 计算出舵机相对于前杆的旋转角度后 *11.375转换成舵机的旋转值
# 由于4、5号舵机连接结构与 3号的不同,
# 3号:角度为正数 逆时针旋转 数值减小 -- 角度为负数 顺时针旋转 数值增大。
# 4、5号:角度为正数 逆时针旋转 数值增大 -- 角度为负数 顺时针旋转 数值减小。
# 所以4、5号舵机需要相加。3号舵机需要相减
angle_5 = int(2047 + int(math.degrees(q1) * 11.375))
angle_4 = int(2047 + int(math.degrees(q2) * 11.375))
angle_3 = int(2047 - int(math.degrees(q3) * 11.375))
# Print the results in radians and degrees
# 分别显示弧度和角度。用math.degrees函数将弧度转换为角度
print("-------------------------")
print("5 = ", int(math.degrees(q1)))
print("4 = ", int(math.degrees(q2)))
print("3 = ", int(math.degrees(q3)))
print("-------------------------")
print("angle_5 = ", angle_5)
print("angle_4 = ", angle_4)
print("angle_3 = ", angle_3)
return angle_3,angle_4,angle_5
import base64
import math
import numpy as np
from aip import AipFace
import cv2
def imagefile2base64(filename):
with open(filename,'rb') as f:
image = base64.b64encode(f.read())
return image.decode('utf-8')
def RotatedRect(center, size, angel):
x,y = center
w,h = size
angelPi = (angel / 180) * math.pi
x1 = x + (w / 2) * math.cos(angelPi) - (h / 2) * math.sin(angelPi)
y1 = y + (w / 2) * math.sin(angelPi) + (h / 2) * math.cos(angelPi)
x2 = x + (w / 2) * math.cos(angelPi) + (h / 2) * math.sin(angelPi)
y2 = y + (w / 2) * math.sin(angelPi) - (h / 2) * math.cos(angelPi)
x3 = x - (w / 2) * math.cos(angelPi) + (h / 2) * math.sin(angelPi)
y3 = y - (w / 2) * math.sin(angelPi) - (h / 2) * math.cos(angelPi)
x4 = x - (w / 2) * math.cos(angelPi) - (h / 2) * math.sin(angelPi)
y4 = y - (w / 2) * math.sin(angelPi) + (h / 2) * math.cos(angelPi)
pts = np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]], np.int32)
return pts
imagepath = r'D:\infer_mask01.jpg'
img = cv2.imread(imagepath)
client = AipFace('31030879','1kC27TZPEqGdM9SyZkvsqL6S','bvLC1k3OZoO2KwWdGNoPZ4nbEA8g91yA')
image = imagefile2base64(imagepath)
imageType = 'BASE64'
options = {"face_field":'age,beauty,gender,landmark',"max_face_num":10}
res = client.detect(image, imageType, options)
if res['error_code'] == 0:
faces=res['result']['face_list']
for face in faces:
s=str(face['age'])+':'+str(face['beauty'])+':'+face['gender']['type']
loc = face['location']
rec=(int(loc['left']),int(loc['top']),int(loc['width']),int(loc['height']))
center=(int(loc['left']+loc['width']/2),int(loc['top']+loc['height']/3))
point_rot=RotatedRect(center,rec[2:],loc['rotation'])
cv2.polylines(img,[point_rot],True,(0,255,0),1)
cv2.imshow(imagepath,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print(res['error_msg'])
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'face2.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(20, 10, 731, 61))
self.label_2.setStyleSheet("background-color: rgb(0, 170, 255);")
self.label_2.setObjectName("label_2")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 70, 581, 471))
font = QtGui.QFont()
font.setFamily("Agency FB")
font.setPointSize(16)
self.label.setFont(font)
# self.label.setLayoutDirection(QtCore.Qt.LeftToRight)
self.label.setStyleSheet("background-color: rgb(85, 170, 255);")
# self.label.setFrameShape(QtWidgets.QFrame.Panel)
# self.label.setFrameShadow(QtWidgets.QFrame.Plain)
self.label.setScaledContents(False)
self.label.setObjectName("label")
self.pushButton3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton3.setGeometry(QtCore.QRect(630, 470, 91, 41))
font = QtGui.QFont()
font.setFamily("Agency FB")
font.setPointSize(12)
self.pushButton3.setFont(font)
self.pushButton3.setStyleSheet("background-color: rgb(85, 85, 127);\n"
"color: rgb(255, 255, 255);")
self.pushButton3.setObjectName("pushButton3")
self.pushButton1 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton1.setGeometry(QtCore.QRect(630, 92, 91, 41))
font = QtGui.QFont()
font.setFamily("Agency FB")
font.setPointSize(12)
self.pushButton1.setFont(font)
self.pushButton1.setAutoFillBackground(False)
self.pushButton1.setStyleSheet("background-color: rgb(0, 85, 255);\n"
"color: rgb(255, 255, 255);")
self.pushButton1.setObjectName("pushButton1")
self.pushButton2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton2.setGeometry(QtCore.QRect(630, 150, 91, 41))
font = QtGui.QFont()
font.setFamily("Agency FB")
font.setPointSize(12)
self.pushButton2.setFont(font)
self.pushButton2.setStyleSheet("background-color: rgb(0, 85, 255);\n"
"color: rgb(255, 255, 255);")
self.pushButton2.setObjectName("pushButton2")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.pushButton3.clicked.connect(MainWindow.close) # type: ignore
self.pushButton1.clicked.connect(MainWindow.slot1) # type: ignore
self.pushButton2.clicked.connect(MainWindow.slot2) # type: ignore
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_2.setText(_translate("MainWindow", "TextLabel"))
self.label.setText(_translate("MainWindow", "人脸识别区域"))
self.pushButton3.setText(_translate("MainWindow", "退出"))
self.pushButton1.setText(_translate("MainWindow", "上传图片"))
self.pushButton2.setText(_translate("MainWindow", "图像识别"))
import sys
import cv2 as cv
import numpy as np
import random
from aip import AipFace
import base64
from PIL import Image, ImageDraw, ImageFont
import pyttsx3
import cv_jichu
import json
import base64
import requests
import math
from PyQt6 import QtWidgets,QtCore
from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
from PyQt6.QtCore import Qt
from face2 import Ui_MainWindow # 导入gui生成的py文件
class QmyWin(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super().__init__() # 调用父类构造函数,创建QMainWindow窗口
self.setupUi(self) # 构造UI界面
def slot1(self):
'''从本地读取图片'''
# 打开文件选取对话框
self.filename, _ = QFileDialog.getOpenFileName(self, '选择图片', '../data/', 'Image files(*.jpg *.gif *.png *.bmp *.jpeg)')
if self.filename:
self.picture = cv.imread(str(self.filename))
# OpenCV图像以BGR通道存储,显示时需要从BGR转到RGB
self.picture = cv.cvtColor(self.picture, cv.COLOR_BGR2RGB)
rows, cols, channels = self.picture.shape
bytesPerLine = channels * cols
QImg = QImage(self.picture.data, cols, rows, bytesPerLine, QImage.Format.Format_RGB888)
self.label.setPixmap(QPixmap.fromImage(QImg))
self.label.setScaledContents(True)
self.label_2.setText(f'图像名称:{self.filename}')
def imagefile2base64(self,filename):
with open(filename, 'rb') as f:
image = base64.b64encode(f.read())
return image.decode('utf-8')
def RotatedRect(self,center, size, angel):
x, y = center
w, h = size
angelPi = (angel / 180) * math.pi
x1 = x + (w / 2) * math.cos(angelPi) - (h / 2) * math.sin(angelPi)
y1 = y + (w / 2) * math.sin(angelPi) + (h / 2) * math.cos(angelPi)
x2 = x + (w / 2) * math.cos(angelPi) + (h / 2) * math.sin(angelPi)
y2 = y + (w / 2) * math.sin(angelPi) - (h / 2) * math.cos(angelPi)
x3 = x - (w / 2) * math.cos(angelPi) + (h / 2) * math.sin(angelPi)
y3 = y - (w / 2) * math.sin(angelPi) - (h / 2) * math.cos(angelPi)
x4 = x - (w / 2) * math.cos(angelPi) - (h / 2) * math.sin(angelPi)
y4 = y - (w / 2) * math.sin(angelPi) + (h / 2) * math.cos(angelPi)
pts = np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]], np.int32)
return pts
def slot2(self):
imagepath = self.filename
img = cv.imread(imagepath)
client = AipFace('31030879', '1kC27TZPEqGdM9SyZkvsqL6S', 'bvLC1k3OZoO2KwWdGNoPZ4nbEA8g91yA')
image = self.imagefile2base64(imagepath)
imageType = 'BASE64'
options = {"face_field": 'age,beauty,gender,landmark', "max_face_num": 10}
res = client.detect(image, imageType, options)
if res['error_code'] == 0:
faces = res['result']['face_list']
print(faces)
for face in faces:
# s = str(face['age']) + ':' + str(face['beauty']) + ':' + face['gender']['type']
loc = face['location']
rec = (int(loc['left']), int(loc['top']), int(loc['width']), int(loc['height']))
center = (int(loc['left'] + loc['width'] / 2), int(loc['top'] + loc['height'] / 3))
point_rot = self.RotatedRect(center, rec[2:], loc['rotation'])
cv.polylines(img, [point_rot], True, (0, 255, 0), 1)
# cv.putText(img, s, rec[:2], cv.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
self.picture1 = img
# OpenCV图像以BGR通道存储,显示时需要从BGR转到RGB
self.picture1 = cv.cvtColor(self.picture1, cv.COLOR_BGR2RGB)
rows1, cols1, channels1 = self.picture1.shape
bytesPerLine1 = channels1 * cols1
QImg = QImage(self.picture1.data, cols1, rows1, bytesPerLine1, QImage.Format.Format_RGB888)
self.label.setPixmap(QPixmap.fromImage(QImg))
self.label.setScaledContents(True)
else:
print(res['error_msg'])
# 程序入口,程序从此处启动PyQt设计的窗体
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = QmyWin()
window.show()
sys.exit(app.exec())