我如何在控制台中打印边界框的坐标并检查此框是否在yolov3中的特定象限中

如何解决我如何在控制台中打印边界框的坐标并检查此框是否在yolov3中的特定象限中

我正在使用预训练的物体检测器,并且正在使用它来检测鸟,狗和猫,但是我想知道的是,如果边界框位于其中一个象限中,那么如何打印到控制台,例如,如果边界框在控制台的第一个象限打印中,则该框在第一个象限中。

这是因为将来我将使它成为我自己的自定义对象检测器,并且我正在练习。我希望你能帮助我。

这是我拥有的代码和象限的图像:

 import numpy as  np
 import cv2

# load the image to detect,get width,height 

img_to_detect = cv2.imread('images/testing/cat_dog_bird.jpg')
img_height = img_to_detect.shape[0]
img_width = img_to_detect.shape[1]

# convert to blob to pass into model
img_blob = cv2.dnn.blobFromImage(img_to_detect,0.003922,(416,416),swapRB=True,crop=False)
#recommended by yolo authors,scale factor is 0.003922=1/255,width,height of blob is 320,320
#accepted sizes are 320×320,416×416,609×609. More size means more accuracy but less speed

# set of 80 class labels 
class_labels = ["person","bicycle","car","motorcycle","airplane","bus","train","truck","boat","trafficlight","firehydrant","stopsign","parkingmeter","bench","bird","cat","dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack","umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sportsball","kite","baseballbat","baseballglove","skateboard","surfboard","tennisracket","bottle","wineglass","cup","fork","knife","spoon","bowl","banana","apple","sandwich","orange","broccoli","carrot","hotdog","pizza","donut","cake","chair","sofa","pottedplant","bed","diningtable","toilet","tvmonitor","laptop","mouse","remote","keyboard","cellphone","microwave","oven","toaster","sink","refrigerator","book","clock","vase","scissors","teddybear","hairdrier","toothbrush"]

#Declare List of colors as an array
#Green,Blue,Red,cyan,yellow,purple
#Split based on ',' and for every split,change type to int
#convert that to a numpy array to apply color mask to the image numpy array
class_colors = ["0,255,0","0,255","255,255"]



class_colors = [np.array(every_color.split(",")).astype("int") for every_color in class_colors]


class_colors = np.array(class_colors)
class_colors = np.tile(class_colors,(16,1))

# Loading pretrained model 
yolo_model = cv2.dnn.readNetFromDarknet('modelo/yolov4.cfg','modelo/yolov4.weights')

# Get all layers from the yolo network
yolo_layers = yolo_model.getLayerNames()

# Loop and find the last layer (output layer) of the yolo network 
yolo_output_layer = [yolo_layers[yolo_layer[0] - 1] for yolo_layer in yolo_model.getUnconnectedOutLayers()]


    
# input preprocessed blob into model and pass through the model
# pasarle el blob al modelo 
yolo_model.setInput(img_blob)

# obtain the detection layers by forwarding through till the output layer
#aqui se le esta pasando el valor de la capa de salida **yolo_output_layer** al modelo con la funcion forward
obj_detection_layers = yolo_model.forward(yolo_output_layer)



# initialization for non-max suppression (NMS)
# declare list for [class id],[box center,width & height[],[confidences]
class_ids_list = []
boxes_list = []
confidences_list = []
cont=0


# loop over each of the layer outputs
#bucle para cada una de las capas de salida
for object_detection_layer in obj_detection_layers:
    # loop over the detections
    for object_detection in object_detection_layer:
        all_scores = object_detection[5:]
        predicted_class_id = np.argmax(all_scores)
        prediction_confidence = all_scores[predicted_class_id]
        

        # take only predictions with confidence more than 20%
        if prediction_confidence > 0.40:
            #get the predicted label
            predicted_class_label = class_labels[predicted_class_id]
            
            #obtain the bounding box co-oridnates for actual image from resized image size
            bounding_box = object_detection[0:4] * np.array([img_width,img_height,img_width,img_height])
            (box_center_x_pt,box_center_y_pt,box_width,box_height) = bounding_box.astype("int")
            start_x_pt = int(box_center_x_pt - (box_width / 2))
            start_y_pt = int(box_center_y_pt - (box_height / 2))
            
            
            #save class id,start x,y,width & height,confidences in a list for nms processing
            #make sure to pass confidence as float and width and height as integers
            class_ids_list.append(predicted_class_id)
            confidences_list.append(float(prediction_confidence))
            boxes_list.append([start_x_pt,start_y_pt,int(box_width),int(box_height)])
            



# Applying the NMS will return only the selected max value ids while suppressing the non maximum (weak) overlapping bounding boxes      
# Non-Maxima Suppression confidence set as 0.5 & max_suppression threhold for NMS as 0.4 (adjust and try for better perfomance)
max_value_ids = cv2.dnn.NMSBoxes(boxes_list,confidences_list,0.5,0.4)

# loop through the final set of detections remaining after NMS and draw bounding box and write text
contD=0
contC=0
contB=0
for max_valueid in max_value_ids:
    max_class_id = max_valueid[0]
    box = boxes_list[max_class_id]
    start_x_pt = box[0]
    start_y_pt = box[1]
    box_width = box[2]
    box_height = box[3]

    #get the predicted class id and label
    predicted_class_id = class_ids_list[max_class_id]
    predicted_class_label = class_labels[predicted_class_id]
    prediction_confidence = confidences_list[max_class_id]
    
    end_x_pt = start_x_pt + box_width
    end_y_pt = start_y_pt + box_height
    
    #get a random mask color from the numpy array of colors
    box_color = class_colors[predicted_class_id]
    
    #convert the color numpy array as a list and apply to text and box
    box_color = [int(c) for c in box_color]
    #object counters
    if predicted_class_label == class_labels[14]:
        contB+=1
    elif predicted_class_label == class_labels[16]:
        contD+=1
    elif predicted_class_label == class_labels[15]:
        contC+=1
    # print the prediction in console
    predicted_class_label = "{}: {:.2f}%".format(predicted_class_label,prediction_confidence * 100)
    print("predicted object {}".format(predicted_class_label))
    
    # draw rectangle and text in the image
    cv2.rectangle(img_to_detect,(start_x_pt,start_y_pt),(end_x_pt,end_y_pt),box_color,1)
    cv2.putText(img_to_detect,predicted_class_label,start_y_pt-5),cv2.FONT_HERSHEY_SIMPLEX,1)

cv2.imshow("Detection Output",img_to_detect)
              
print("\n")
if contB > 0 and contD > 0 and contC > 0:
    print("This Photo has a dog,a cat and a bird")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res