2023年12月6日发(作者:大众crossblue)

用yolov3进行图片分类

使用yoloV3进行图片分类:一个待处理的Images文件夹,里面包含要处理的图片;一个目标文件personFile,我这里需要提取含有

行人的图片;一个非目标的文件noPersonFile。实际功能是从Images一张一张的读取,使用yolo返回的结果查看该图片是否包含行人,有

则把它写入personFile文件中,否则写入noPersonFile文件中,同时将该图片从Images删除(处理的图片有点多,怕突然中断又要重头开

始)。

运行该程序需要确保Images文件夹在当前工作目录,同时需要把拷贝到当前工作目录。

# -*- coding: utf-8 -*-

# Author: weiz

# Date: 2019/9/16 17:00

# Name: test_yolo

# Description: YOLOv3目标检测的代码,提供检测的接口;也可以单独运行

import cv2

import numpy as np

class Yolo:

def __init__(self, cfgPath, weightPath, labelNamesPath):

h = cfgPath

Path = weightPath

ames = labelNamesPath

t = t(h, Path)

= open(labelNamesPath).read().strip().split(\"n\")

= len()

= t(0, 255, size=(, 3), dtype=\'uint8\')

def detect(self, img, confidThr=0.5, nmsThr=0.3, isDraw=False):

(h, w) = [:2]

# 获取YOLO输出层的名字

ln = erNames()

ln = [ln[i[0] - 1] for i in onnectedOutLayers()]

# 将图片构建成一个blob,设置图片尺寸,然后执行一次

# YOLO前馈网络计算,最终获取边界框和相应概率

blob = omImage(img, 1 / 255.0, (416, 416), swapRB=True, crop=False)

ut(blob)

layerOutputs = d(ln)

# 初始化边界框,置信度(概率)以及类别

boxes = []

confidences = []

classIDs = []

# 迭代每个输出层,总共三个

for output in layerOutputs:

# 迭代每个检测

for detection in output:

# 提取类别ID和置信度

scores = detection[5:]

classID = (scores)

confidence = scores[classID]

# 只保留置信度大于某值的边界框

if confidence > confidThr:

# 将边界框的坐标还原至与原图片相匹配,记住YOLO返回的是

# 边界框的中心坐标以及边界框的宽度和高度

box = detection[0:4] * ([w, h, w, h])

(centerX, centerY, width, height) = (\"int\")

# 计算边界框的左上角位置

# 计算边界框的左上角位置

x = int(centerX - (width / 2))

y = int(centerY - (height / 2))

# 更新边界框,置信度(概率)以及类别

([x, y, int(width), int(height)])

(float(confidence))

(classID)

# 使用非极大值抑制方法抑制弱、重叠边界框

idxs = es(boxes, confidences, confidThr, nmsThr)

lab = []

loc = []

# 确保至少一个边界框

if len(idxs) > 0:

# 迭代每个边界框

for i in n():

# 提取边界框的坐标

(x, y) = (boxes[i][0], boxes[i][1])

(w, h) = (boxes[i][2], boxes[i][3])

# 绘制边界框以及在左上角添加类别标签和置信度

text = \'{}: {:.3f}\'.format([classIDs[i]], confidences[i])

if isDraw:

color = [int(c) for c in [classIDs[i]]]

gle(img, (x, y), (x + w, y + h), color, 2)

(text_w, text_h), baseline = tSize(text, _HERSHEY_SIMPLEX, 0.5, 2)

gle(img, (x, y - text_h - baseline), (x + text_w, y), color, -1)

t(img, text, (x, y - 5), _HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)

text_inf = text + \' \' + \'(\' + str(x) + \',\' + str(y) + \')\' + \' \' + \'宽:\' + str(w) + \'高:\' + str(h)

([x, y, w, h])

#(text_inf)

([classIDs[i]])

return lab, img, loc

labelPath = \'./cfg/\'

cfgPath = \'./cfg/yolov3_\'

weightPath = \'./cfg/s\'

yolo = Yolo(cfgPath, weightPath, labelPath)

if __name__ == \'__main__\':

cap = apture(\"./\")

while True:

ret, img = ()

if ret is False:

exit()

lab, retImg, loc = (img, isDraw=True)

(\'video\', retImg)

if y(1) & 0xFF == 27:

e() # 关闭摄像头

yAllWindows()

break

,分类代码如下:

# -*- coding: utf-8 -*-#

# Author: weiz

# Date: 2019/10/12 14:18

# Name: detectImageIsPerson

# Description:

import os

import sys

import cv2 as cv

import yolomain

import copy

def checkFileExist(fileName, isCreate=None):

\"\"\"

检测当前工作目录下fileName文件是否存在,并根据isCreate是否创建

:param fileName:文件夹名字

:param isCreate:是否创建

:return:不存在返回false,存在或者创建返回true

\"\"\"

if isCreate == True:

isCreate = True

else:

isCreate = False

if (fileName):

return True

else:

if isCreate:

rs(fileName)

return True

else:

return False

if __name__ == \'__main__\':

workSpace = ()

imagesFile = \"Images\"

personFile = \"personFile\"

noPersonFile = \"noPersonFile\"

print(\"The workspace:{}\".format(workSpace))

print(checkFileExist(imagesFile))

print(checkFileExist(personFile, True))

print(checkFileExist(noPersonFile, True))

imagesPath = (workSpace, imagesFile)

print(\"Reading pictures from {}\".format(imagesPath))

personPath = (workSpace, personFile)

noPersonPath = (workSpace, noPersonFile)

imagelist = r(imagesPath)

if imagelist == []:

print(\"The {} is not contain images\".format(imagesPath))

(0)

# 检测图片中是否存在person

frame = 1

for imgName in imagelist:

print(\"Processing the {}\".format(frame))

imgPath = (imagesPath, imgName)

imgPath = h(imgPath)

# 读取图片

img = (imgPath)

retImg = py(img)

e1 = kCount()

_, _, out_classes = _ser(retImg)

e2 = kCount()

time = (e2 - e1) / kFrequency()

# 写入图片

personName = (personPath, imgName)

personName = h(personName)

personName = h(personName)

noPersonName = (noPersonPath, imgName)

noPersonName = h(noPersonName)

isPerson = False

for objectClass in out_classes:

if objectClass == \'person\':

isPerson = True

e(personName, img)

(imgPath)

break

if not isPerson:

e(noPersonName, img)

(imgPath)

print(\"It took {:.2f} seconds to complete the {}th frame picture.\".format(time, frame))

frame = frame + 1

20201012-------更新

更加完善的过滤,下面包含图片或视频数据的筛选:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @Time :2020/10/10 10:30

# @Author :weiz

# @ProjectName :pycharmProject

# @File :

import os

import cv2

import yolomain

import copy

def checkFileExist(fileName, isCreate=None):

\"\"\"

检测当前工作目录下fileName文件是否存在,并根据isCreate是否创建

:param fileName:文件夹名字

:param isCreate:是否创建

:return:不存在返回false,存在或者创建返回true

\"\"\"

if isCreate == True:

isCreate = True

else:

isCreate = False

if (fileName):

return True

else:

if isCreate:

rs(fileName)

return True

else:

print(\"the [{}] folder does not exist\".format(fileName))

return False

def videosFilter(videosPath, gap, savePath, filterGarget):

\"\"\"

分离视频中含有目标的图片

:param videoPath:视频路径,只能处理一级图片

:param gap:每隔多少帧才处理

:param savePath:保存路径

:param filterGarget:分离的目标类别

:param filterGarget:分离的目标类别

:return:

\"\"\"

checkFileExist(savePath, True)

videoLists = r(videosPath)

for videoName in videoLists:

videoPath = (videosPath, videoName)

videoNamePrefix = (\'.\')[0]

saveVideoPath = (savePath, videoNamePrefix)

checkFileExist(saveVideoPath, True)

print(videoPath)

cap = apture(videoPath)

ret = True

frames = 0

while ret:

ret, img = ()

saveImg = py(img)

labs = []

if frames % gap == 0:

labs, _, _ = (img, isDraw=True)

else:

frames = frames + 1

continue

for label in labs:

if label == filterGarget:

imgName = videoNamePrefix + \'_\' + \"{:0>6d}\".format(frames) + \".png\"

imgName = (saveVideoPath, imgName)

print(imgName)

e(imgName, saveImg)

break

(\'video\', img)

#(\"saveImg\", saveImg)

if y(1) & 0xFF == 27:

e() # 关闭摄像头

yAllWindows()

break

print(frames)

frames = frames + 1

yAllWindows()

def imagesFilter(imagesFilePath, savePath, filterGarget):

\"\"\"

分离图片中含有目标的图片

:param imagesFilePath:

:param savePath:

:param filterGarget:

:return:

\"\"\"

workSpace = ()

if not checkFileExist(imagesFilePath):

exit()

checkFileExist(savePath, True)

print(\"The workspace:{}\".format(workSpace))

print(\"Reading pictures from {}\".format(imagesFilePath))

targetFile = filterGarget + \"File\"

nontargetFile = \"no\" + filterGarget + \"File\"

targetFilePath = (savePath, targetFile)

nontargetFilePath = (savePath, nontargetFile)

checkFileExist(targetFilePath, True)

checkFileExist(nontargetFilePath, True)

fileLists = r(imagesFilePath)

# print(fileLists)

for fileList in fileLists:

fileListPath = (imagesFilePath, fileList)

if (fileListPath): # 处理第一级的图片

img = (fileListPath)

e1 = kCount()

lab, img, loc = (img)

e2 = kCount()

time = (e2 - e1) / kFrequency()

targetSaveName = (targetFilePath, fileList)

nontargetSaveName = (nontargetFilePath, fileList)

isPerson = False

for objectClass in lab:

if objectClass == filterGarget:

isPerson = True

e(targetSaveName, img)

break

if not isPerson:

e(nontargetSaveName, img)

(fileListPath)

else: # 处理第二级的图片

imgsNames = r(fileListPath)

# print(imgsNames)

targetFilePath_sub = (targetFilePath, fileList)

nontargetFilePath_sub = (nontargetFilePath, fileList)

checkFileExist(targetFilePath_sub, True)

checkFileExist(nontargetFilePath_sub, True)

for imgName in imgsNames:

imgNamePath = (fileListPath, imgName)

# print(imgNamePath)

img = (imgNamePath)

e1 = kCount()

lab, img, loc = (img)

e2 = kCount()

time = (e2 - e1) / kFrequency()

targetSaveName = (targetFilePath_sub, imgName)

nontargetSaveName = (nontargetFilePath_sub, imgName)

isPerson = False

for objectClass in lab:

if objectClass == filterGarget:

isPerson = True

e(targetSaveName, img)

break

if not isPerson:

e(nontargetSaveName, img)

(imgNamePath)

print(\"The [{}] folder has been processed!\".format(fileListPath))

videosFilePath = \"./videos\" # 视频文件夹,处理如下文件格式:

# ./videos

#

#

imagesFilePath = \"./images1\" # 图片文件夹,只能处理两级文件如下所示:

# ./images

# /001

#

#

savePath = \"./ret\"

filterGarget = \"person\"

if __name__ == \'__main__\':

videosFilter(videosFilePath, 11, savePath, filterGarget) videosFilter(videosFilePath, 11, savePath, filterGarget) #imagesFilter(imagesFilePath, savePath, filterGarget)

更多推荐

图片,边界,处理,文件