简体   繁体   English

在 python 的字典中存储坐标

[英]Store coordinates in a dictionary in python

From a set of code, I got an output of coordinates like从一组代码中,我得到了一个 output 的坐标,例如

(448, 258)
(445, 362)
(426, 784)
(441, 496)

I need to store them in a dictionary.我需要将它们存储在字典中。 I want to iterate through the dictionary's elements after the coordinates stored in it.我想在存储在其中的坐标之后遍历字典的元素。 Also, the coordinates are not constant they may vary from one file to other( the number of coordinates may change and value of 'x' and 'y' also ).此外,坐标不是恒定的,它们可能会因文件而异(坐标数可能会发生变化,并且“x”和“y”的值也会发生变化)。 So it should not be hardcoded.所以它不应该被硬编码。 How can I make it possible using python?如何使用 python 使其成为可能? I am a noob, please guide me.我是菜鸟,请指导我。

If it is not possible the coordinates are obtained from a function giving outputs of x and y.如果不可能,则从 function 获得坐标,给出 x 和 y 的输出。 Can we form the coordinate dictionary from this?我们可以由此形成坐标字典吗?

Edit:编辑:

I expect the output as {(448, 258), (445, 362), (426, 784), (441, 496)} Also, have a doubt if I get the output as I expected can I make a loop through it like for x in dict ?我希望 output 为{(448, 258), (445, 362), (426, 784), (441, 496)}另外,如果我得到 output 有疑问,我可以通过它进行循环喜欢for x in dict吗?

The code follows代码如下

import numpy as np
import argparse
import time
import cv2
import os


ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image")
ap.add_argument("-y", "--yolo", required=True, help="base path to YOLO directory")
ap.add_argument("-c", "--confidence", type=float, default=0.5, help="minimum probability to filter weak detections")
ap.add_argument("-t", "--threshold", type=float, default=0.3, help="threshold when applying non-maxima suppression")
args = vars(ap.parse_args())
counts = dict()

labelsPath = os.path.sep.join([args["yolo"], "coco.names"])
LABELS = open(labelsPath).read().strip().split("\n")

np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8")
weightsPath = os.path.sep.join([args["yolo"], "yolov3.weights"])
configPath = os.path.sep.join([args["yolo"], "yolov3-320.cfg"])
print("[INFO] loading YOLO from disk...")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)

image = cv2.imread(args["image"])
(H, W) = image.shape[:2]
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
start = time.time()
layerOutputs = net.forward(ln)
end = time.time()
print("[INFO] YOLO took {:.6f} seconds".format(end - start))

boxes = []
confidences = []
classIDs = []

for output in layerOutputs:
    for detection in output:
        scores = detection[5:]
        classID = np.argmax(scores)
        confidence = scores[classID]
        if confidence > args["confidence"]:
            box = detection[0:4] * np.array([W, H, W, H])
            (centerX, centerY, width, height) = box.astype("int")
            x = int(centerX - (width / 2))
            y = int(centerY - (height / 2))
            boxes.append([x, y, int(width), int(height)])
            confidences.append(float(confidence))
            classIDs.append(classID)

idxs = cv2.dnn.NMSBoxes(boxes, confidences, args["confidence"], args["threshold"])

if len(idxs) > 0:
    for i in idxs.flatten():
        (x, y) = (boxes[i][0], boxes[i][1])
        (w, h) = (boxes[i][2], boxes[i][3])
        color = [int(c) for c in COLORS[classIDs[i]]]
        rectangle = cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
        text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
        cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

        x1= y+h
        y1= x+w
        coordinates = (x1,y1)
        print(coordinates)

I have written the print statement for knowing the coordinates of the boxes that was produced after the object detection.我已经编写了打印语句以了解在 object 检测后生成的框的坐标。

In order to take one tuple and seperate the element into a dict, this works:为了获取一个元组并将元素分离到一个字典中,这有效:

t = (440, 765)
dict = {}
print(dict)
dict[t[0]] = t[1]
print(dict)

And the output is: output 是:

{}
{440: 765}

This should work as long as you are only giving it one tuple at a time, and none of the x-coordinates are the same.只要您一次只给它一个元组,并且所有 x 坐标都不相同,这应该可以工作。 This could be re-rganized into a function like so:这可以重新组织为 function ,如下所示:

def make_dict(tuple, dict):
     dict[tuple[0]] = tuple[1]

Ok, I see you are just printing the coordinates out.好的,我看到您只是在打印坐标。 You need to collect them as you go, so you might as well collect them directly into a set() :您需要像 go 一样收集它们,因此您不妨将它们直接收集到set()

out = set()
if len(idxs) > 0:
    for i in idxs.flatten():
        (x, y) = (boxes[i][0], boxes[i][1])
        (w, h) = (boxes[i][2], boxes[i][3])
        color = [int(c) for c in COLORS[classIDs[i]]]
        rectangle = cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
        text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
        cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

        x1= y+h
        y1= x+w
        out.add( (x1,y1) )
print(out)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM