记录一下怎么使用pycaffe调用已有的网络模型识别人脸(物体)

我的哲学原理:比较喜欢从结果向前推,有了能做什么、再去学怎么做?


今天就来看看怎么从图片中识别出人脸:



代码很简单,直接上码:


# -*- coding: utf-8 -*
import numpy as np  
import sys,os  
import cv2
caffe_root = 'E:/bigdata/workspace/caffe-ssd-microsoft/'
sys.path.insert(0, caffe_root + 'python')  
import caffe  
import time;  


net_file= 'faceboxes_deploy.prototxt'  
caffe_model='FaceBoxes_1024x1024.caffemodel'  
test_dir = "images"

#
if not os.path.exists(caffe_model):
    print("FaceBoxes_deploy.caffemodel does not exist,")
    print("use merge_bn.py to generate it.")
    exit()
#
caffe.set_mode_cpu()#gpu
net = caffe.Net(net_file,caffe_model,caffe.TEST) #加载network和model

#分类类别
CLASSES = ('background',
           'face')

#设定图片的shape格式(1,3,1024,1024)
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) 
transformer.set_transpose('data', (2,0,1)) #改变维度的顺序,由原始图片(H,W,C)变为(C,H,W)
transformer.set_mean('data', np.array([104,117,123]))  # mean pixel
#transformer.set_raw_scale('data', 255);    # 缩放到[0,255]之间
#transformer.set_channel_swap('data', (2,1,0));   #交换通道,将图片由RGB变为BGR

def preprocess(src):
    img = cv2.resize(src, (1024,1024))
    img = img - 127.5
    img = img * 0.007843
    return img

def postprocess(img, out):   
    h = img.shape[0]
    w = img.shape[1]
    box = out['detection_out'][0,0,:,3:7] * np.array([w, h, w, h])

    cls = out['detection_out'][0,0,:,1]
    conf = out['detection_out'][0,0,:,2]
    return (box.astype(np.int32), conf, cls)

def detect_ok(imgfile):
    
    frame = cv2.imread(imgfile)
    print(frame.shape, frame.ndim, frame.size,frame.dtype, frame.itemsize)
    if frame.ndim<0:
        return False
    #cv2.imshow("org", frame)
    #cv2.waitKey(1000)
    
    # image shape info
    #rows, cols, channels = frame.shape
    height, width, channels = frame.shape
    res = cv2.resize(frame, (1024, 1024), 0.0, 0.0, interpolation=cv2.INTER_CUBIC)
    #cv2.imshow("org", res)
    #cv2.waitKey(1000)
    
    #转成caffe能识别的图片格式
    #res=cv2.cvtColor(res,cv2.COLOR_BGR2RGB)
    res=res/255.
    
    # net input shape info    
    print(net.blobs['data'].data.shape)#input 1,3,1024,1024
    transformed_image = transformer.preprocess('data', res)#frame      
    #cv2.imshow("org", transformed_image)
    #cv2.waitKey(1000)
    
    # 执行上面设置的图片预处理操作,并将图片载入到blob中
    net.blobs['data'].data[...] = transformed_image
    
    time_start=time.time()
    out = net.forward() #运行前向网络预测
    time_end=time.time()
    print(time_end-time_start,"s") 
    
    #显示结果
    box, conf, cls = postprocess(frame, out)
    
    for i in range(len(box)):
        p1 = (box[i][0], box[i][1])
        p2 = (box[i][2], box[i][3])
        cv2.rectangle(frame, p1, p2, (0,255,0), 2)
        p3 = (max(p1[0], 15), max(p1[1], 15))
        title = "%s:%.2f" % (CLASSES[int(cls[i])], conf[i])
        cv2.putText(frame, title, p3, cv2.FONT_ITALIC, 0.6, (0, 255, 0), 2)
    #
    frame = cv2.resize(frame, (int(width/2), int(height/2)), interpolation=cv2.INTER_CUBIC)
    cv2.imshow("org", frame)
    cv2.waitKey(2000)
    return True
     
    

#test here!!!
for f in os.listdir(test_dir):
    if detect_ok(test_dir + "/" + f) == False:
       break


模型文件参见:

https://github.com/zeusees/FaceBoxes


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Android Studio中使用虹软人脸识别本地的人脸数据库并调用网络训练模型进行人脸识别的步骤如下: 1. 在项目的build.gradle文件中添加虹软人脸识别库的依赖: ``` implementation 'com.arcsoft:libarcsoft-face:2.1.1' ``` 2. 在代码中使用FaceEngine类的静态方法createHandle()创建人脸识别引擎的句柄: ``` FaceEngine faceEngine = new FaceEngine(); int faceEngineCode = faceEngine.createHandle(context, appId, sdkKey); ``` 其中,context为上下文对象,appId和sdkKey为在虹软官网申请的应用ID和SDKKey。 3. 加载训练好的人脸识别模型文件: ``` faceEngineCode = faceEngine.setFaceRecognizeModelPath("assets/model/recognition"); ``` 4. 初始化人脸识别引擎: ``` faceEngineCode = faceEngine.init(context, DetectMode.ASF_DETECT_MODE_IMAGE, DetectFaceOrientPriority.ASF_OP_0_ONLY, 16, 1, FaceEngine.ASF_FACE_RECOGNITION | FaceEngine.ASF_FACE_DETECT | FaceEngine.ASF_FACE_MODEL); faceEngineCode = faceEngine.setLivenessParam(0.5f, 0.7f); ``` 其中,setLivenessParam()方法用于设置活体检测的参数,0.5f和0.7f分别表示活体检测的阈值和活体检测的动作阈值。 5. 加载人脸数据库: ``` List<FaceDB.FaceRegist> faceList = new ArrayList<>(); faceList.addAll(mFaceDB.getRegisterData()); faceEngineCode = faceEngine.registeredFaceList(faceList); ``` 其中,mFaceDB为人脸数据库对象,getRegisterData()方法用于获取人脸数据库中的注册数据。 6. 调用人脸识别引擎的相关方法进行人脸识别。 需要注意的是,在使用虹软人脸识别本地的人脸数据库并调用网络训练模型进行人脸识别时,需要对人脸数据库进行充分的处理和优化,以提高识别的准确率和稳定性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值