基于YOLO的区域检测
最近在研究YOLO的项目,也研究一些大神关于区域检测的代码,发现比较稀缺,几番周折之后,研究了一下,搞了一套暂且能凑合用的,先码上,免得以后自己忘了。
一、使用步骤
1.判断点是否在多边形内部的
代码如下:
def is_poi_in_poly(pt, poly):
"""
判断点是否在多边形内部的 pnpoly 算法
:param pt: 点坐标 [x,y]
:param poly: 点多边形坐标 [[x1,y1],[x2,y2],...]
:return: 点是否在多边形之内
"""
nvert = len(poly)
vertx = []
verty = []
testx = pt[0]
testy = pt[1]
for item in poly:
vertx.append(item[0])
verty.append(item[1])
j = nvert - 1
res = False
for i in range(nvert):
if (verty[j] - verty[i]) == 0:
j = i
continue
x = (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]
if ((verty[i] > testy) != (verty[j] > testy)) and (testx < x):
res = not res
j = i
return res
2.检测物体是否在多边形危险区域内
代码如下:
def in_poly_area_dangerous(xyxy,area_poly):
"""
检测人体是否在多边形危险区域内
:param xyxy: 人体框的坐标
:param img_name: 检测的图片标号,用这个来对应图片的危险区域信息
:return: True -> 在危险区域内,False -> 不在危险区域内
"""
# print(area_poly)
if not area_poly: # 为空
return False
# 求物体框的中点
object_x1 = int(xyxy[0])
object_y1 = int(xyxy[1])
object_x2 = int(xyxy[2])
object_y2 = int(xyxy[3])
object_w = object_x2 - object_x1
object_h = object_y2 - object_y1
object_cx = object_x1 + (object_w / 2)
object_cy = object_y1 + (object_h / 2)
return is_poi_in_poly([object_cx, object_cy], area_poly)
3.推理中的修改
代码如下:
if det is not None and len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], image.shape).round()
for *xyxy, conf, cls in det:
image_result = {}
if names[int(cls)] == "black_car":
if in_poly_area_dangerous(xyxy,area_poly) == True:
4.调用
代码如下:
if __name__ == '__main__':
area_poly = [[6,138],[1277,133],[1275,718],[4,719]] #坐标点
ModelPath = './model/best.pt'
Device = select_device('cpu') # # cpu:cpu, GPU:0,1,2
Model = load_model(ModelPath, Device)
ImgPath = '71.jpg'
Image = cv2.imread(ImgPath)
print(predict(Model,Image,Device))
以上就是全部代码和实现过程,图就不放了,懒得搞了
版权声明:本文为CSDN博主「徘徊__」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zcblcz/article/details/121508369
暂无评论