人体识别
一、调用百度api
1.1、调用百度api
import requests
import base64
'''
人体检测和属性识别
'''
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_attr"
# 二进制方式打开图片文件
f = open('333.jpg', 'rb')
img = base64.b64encode(f.read())
params = {"image":img}
access_token = '24.36e88ef07a6d15e9465a2040fe318157.2592000.1611302059.282335-23260441'
# access_token 一个月需一换
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
print (response.json())
333.jpg原图为:
运行代码后返回结果:
可以看出,有四个人被检测出来了,还有坐标信息等
可以看到,其中一个坐标为,177,1040,219,430
219,430分别代表物体检测出的高于宽
177,与1040,代表与左上角坐标(0,0)的距离值
1.2、框出一个行人
我们刚刚知道了其中一个行人的坐标
现在使用opencv把他先框出
框出一个行人的源码:
import cv2
img = cv2.imread('333.jpg')
# 起点和终点的坐标
ptStart = (1040, 177)
ptEnd = (1040+219, 177)
point_color = (0, 255, 0) # BGR
thickness = 2
lineType = 4
cv2.line(img, ptStart, ptEnd, point_color, thickness, lineType)
ptStart = (1040, 177)
ptEnd = (1040, 177+430)
point_color = (0, 255, 0) # BGR
thickness = 2
lineType = 4
cv2.line(img, ptStart, ptEnd, point_color, thickness, lineType)
ptStart = (1040, 177+430)
ptEnd = (1040+219, 177+430)
point_color = (0, 255, 0) # BGR
thickness = 2
lineType = 4
cv2.line(img, ptStart, ptEnd, point_color, thickness, lineType)
ptStart = (1040+219, 177)
ptEnd = (1040+219, 177+430)
point_color = (0, 255, 0) # BGR
thickness = 2
lineType = 4
cv2.line(img, ptStart, ptEnd, point_color, thickness, lineType)
cv2.imshow('demo', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
效果:
1.3、框出全部行人
这里我们对1.2和1.1的代码合并,并稍作修改
# encoding:utf-8
import requests
import base64
import cv2
'''
人体检测和属性识别
'''
# 调用百度api获取数据
def acquire(img_url):
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_attr"
# 二进制方式打开图片文件
f = open(img_url, 'rb')
img = base64.b64encode(f.read())
params = {"image": img}
access_token = '24.36e88ef07a6d15e9465a2040fe318157.2592000.1611302059.282335-23260441'
# access_token 需一个月一换
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
data = response.json() # 保存获取到的json数据
return data
def drawline(data, img): # 把图片框出来
num = data["person_num"]
for k in range(num):
local = data["person_info"][k]['location'] # 图片的位置信息
ptStart = [(local["left"], local["top"]), # 起点和终点的坐标 4个点 画四条线, 相当于一个正方形
(local["left"], local["top"]),
(local["left"], local["top"] + local["height"]),
(local["left"] + local["width"], local["top"])]
ptEnd = [(local["left"] + local["width"], local["top"]),
(local["left"], local["top"] + local["height"]),
(local["left"] + local["width"], local["top"] + local["height"]),
(local["left"] + local["width"], local["top"] + local["height"])]
point_color = (0, 255, 0) # BGR
thickness = 2
lineType = 4
for i in range(4):
cv2.line(img, ptStart[i], ptEnd[i], point_color, thickness, lineType)
print (num)
# print(data["person_info"][0]['location']["top"])
# print(data["person_info"][0]['location'])
if __name__ == '__main__':
img_url = '333.jpg'
data = acquire(img_url) # 调用百度api获取数据
img = cv2.imread(img_url) # 加载图片
drawline(data, img)
cv2.imshow('demo', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
实验效果:
这里需要注意的是 access_token 可能会过期,大家需要到百度ai平台上自行获取
二、创建Django
2.1、创建虚拟环境
首先安装虚拟环境,命令如下:
pip3 install virtualenv #安装虚拟环境
接下来还要安装虚拟环境扩展包,命令如下:
pip3 install virtualenvwrapper
创建虚拟环境的命令如下:
mkvirtualenv 虚拟环境名称 # mkvirtualenv -p python3 虚拟环境名字
例:
mkvirtualenv django_1
查看安装已安装的包
pip list
pip freeze
安装jango
指定清华镜像源,下载速度更快。
sudo pip3 install Django==2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
退出虚拟环境的命令如下:
deactivate
使用虚拟环境的命令如下:
写出名称的前部分后,可以使用tab键补齐
workon 虚拟环境名称
例:
workon django_1
删除虚拟环境命令如下:
rmvirtualenv 虚拟环境名称
例:
先退出: deactivate
再删除: rmvirtualenv django_1
查看jango安装是否成功
输入 django-admin
如上图表示安装成功
如果没有出现,则需自己配置环境变量
2.2、创建jango项目
django-admin startproject demo1
jango目录结构:
2.3、创建jango应用
创建一个名为peopletest的应用
cd demo1
python manage.py startapp peopletest
目录结构:
2.4、运行jango应用
修改demo1/settings.py,
在INSTALLED_APPS目录中添加 ‘peopletest’
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'peopletest'
]
运行jango
python manage.py runserver
在浏览器访问127.0.0.1:8000
2.5、编写第一个页面
peopletest/view.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
在peopletest 目录里新建一个 urls.py 文件
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
修改demo1/url.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('peopletest/', include('peopletest.urls')),
]
运行
python manage.py runserver
访问http://127.0.0.1:8000/peopletest/
显示页面如下:
2.6、创建数据库
创建question表和choice表
其中question表包含question_text 字段和 pub_date字段
choice表包含 question,choice_text,votes 字段
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
修改demo1/settings.py文件
添加’peopletest.apps.PeopletestConfig’
INSTALLED_APPS = [
'peopletest.apps.PeopletestConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 'peopletest'
]
使用以下命令创建数据库
python manage.py makemigrations peopletest
python manage.py migrate
用navicat打开sqllite导入刚刚创建的db.sqlite3
导入后发现db.sqlite3的表结构如下图所示
2.7、使用shell数据交互
这里建议参考官方文档
python manage.py shell #进入shell
from peopletest.models import Choice, Question
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now()) #插入数据
q.save() #保存
q.id # 查询
q.question_text
q.pub_date
2.8、Django 管理页面
python manage.py createsuperuser
Username: admin
Email address: admin@example.com
最后一步是输入密码。你会被要求输入两次密码,第二次的目的是为了确认第一次输入的确实是你想要的密码。
Password: **********
Password (again): *********
运行
python manage.py runserver
修改peopletest/admin.py,添加引用
from django.contrib import admin
from .models import Question
admin.site.register(Question)
可以发现多出了一个列表
3、添加字段
class User(models.Model):
name = models.CharField(verbose_name='姓名', max_length=10)
avator = models.ImageField(verbose_name='头像', upload_to='upload/%Y/%m/%d')
sex = models.CharField(verbose_name='性别', max_length=10)
age = models.CharField(verbose_name='年龄', max_length=10)
upper_wear = models.CharField(verbose_name='上装', max_length=10)
lower_wear = models.CharField(verbose_name='下装', max_length=10)