Python 如何解决多处理错误:;名称错误:名称';W';“未定义”;

Python 如何解决多处理错误:;名称错误:名称';W';“未定义”;,python,multithreading,multiprocessing,Python,Multithreading,Multiprocessing,我在尝试优化视频上运行的对象检测代码时遇到此错误。代码进行初始检测,然后处理它们以获得边界框和类索引。传递给池.map\u async函数的目标函数是: def process_detection( detections ): for detection_level in detections: for detection in detection_level: # print(detection.shape) # (85,)

我在尝试优化视频上运行的对象检测代码时遇到此错误。代码进行初始检测,然后处理它们以获得边界框和类索引。传递给
池.map\u async
函数的目标函数是:

  def process_detection( detections ):
    for detection_level in detections:
            for detection in detection_level:
                # print(detection.shape)  # (85,) shape
                xcenter, ycenter, width, height = np.asarray([W, H, W, H]) * detection[0:4]
                confidence_encoded = detection[5:] # (80,) array
                index_class = np.argmax(confidence_encoded) #index of max confidence
                confidence = confidence_encoded[index_class] # float value of confidence (probability)
                class_predicted = classes[index_class] # class predicted

                # print(class_predicted)
                if confidence > 0.5:
                    if class_predicted == "person":
                        print("{} , {:.2f}".format(class_predicted, confidence))
                        # continue
                        topX = int(xcenter - width/2.)
                        topY = int(xcenter - height/2.)
                        width = int(width)
                        height = int(height)
                        confidence = float(confidence)

                        bbox = [topX, topY, width, height]
                        
                        boxes.append(bbox)
                        confidences.append(confidence)
                        classIDs.append(index_class)
                        classes_pred.append(class_predicted)
    
    return [boxes, confidences, classIDs, classes_pred]   

但是我从multiprocessing\pool.py文件中得到了一个非常奇怪的错误:

回溯(最近一次呼叫最后一次):
文件“C:\Users\naqas\OneDrive\Desktop\tracking\u code\u new.py”,第181行,在
main()
文件“C:\Users\naqas\OneDrive\Desktop\tracking\u code\u new.py”,主目录第134行
RESULTS=RESULTS.get()
get中第657行的文件“C:\Users\naqas\Anaconda3\lib\multiprocessing\pool.py”
提升自我价值
NameError:未定义名称“W”
代码的相关部分如下所示:

def main():
    pool = Pool(processes=os.cpu_count()) # make a process pool  for multi-processing 

    path = Path("C:/","Users","naqas","Downloads","content","gdrive","My Drive","YOLOv3")
    classes = open(str(path.joinpath("coco.names")), "r").read().strip().split("\n")
    colors = np.random.randint(0,255,(1000,3),dtype="uint8") 


    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #                reading the video
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


    cap = cv2.VideoCapture(str(path.joinpath("video_.mp4")))

    _, frame = cap.read()

    if frame is None:
        print(f"FRAME IS NOT READ")
    else:
        # frame = resize(frame, width=500)
        H, W = frame.shape[0:2]

    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #                <model>
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    configPath = path.joinpath("yolov3.cfg")
    weightsPath = path.joinpath("yolov3.weights")
     

    net = cv2.dnn.readNetFromDarknet(str(configPath), str(weightsPath))
    ln = net.getLayerNames()
    ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]



    writer = None 


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

    fps_ = FPS().start()
    i = 0
    
    while True:
        try:
            if writer is None:

                writer = cv2.VideoWriter("./detections.avi", cv2.VideoWriter_fourcc(*"MJPG"), cv2.CAP_PROP_FPS, (W, H))

            _, frame = cap.read() # reading the frame
            # frame = resize(frame, width=W) # resizing the frame 

            blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), 
            swapRB=True, crop=False) # yolov3 version 

            net.setInput(blob) 

            start = time()
            detections = net.forward(ln)
            end = time() 
            print(f"{(end-start):.2f} seconds taken for detection")

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            #                after detection
            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            # print(len(detections)) # detections from 3 levels
            # print(detections[0].shape, detections[-1].shape)  # detections are in [N, D] format with D = 85
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            results = pool.map_async(process_detection, detections)
            pool.close()
            pool.join()
            print(results)
            # boxes, confidences, classIDs, classes_pred = results.get()
            RESULTS = results.get()

def main():
pool=pool(processs=os.cpu_count())#为多处理创建一个进程池
路径=路径(“C:/”、“用户”、“纳卡”、“下载”、“内容”、“gdrive”、“我的驱动器”、“YOLOv3”)
classes=open(str(path.joinpath(“coco.names”),“r”).read().strip().split(“\n”)
colors=np.random.randint(0255,(1000,3),dtype=“uint8”)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#阅读视频
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cap=cv2.VideoCapture(str(path.joinpath(“video.mp4”))
_,frame=cap.read()
如果框架为无:
打印(f“未读取帧”)
其他:
#框架=调整大小(框架,宽度=500)
H、 W=框架形状[0:2]
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#                
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
configPath=path.joinpath(“yolov3.cfg”)
weightsPath=path.joinpath(“yolov3.weights”)
net=cv2.dnn.readNetFromDarknet(str(configPath),str(weightsPath))
ln=net.getLayerNames()
ln=[ln[i[0]-1]表示net.getUnconnectedOutLayers()中的i
writer=无
框=[]
信任=[]
ClassID=[]
类_pred=[]
fps=fps().start()
i=0
尽管如此:
尝试:
如果writer为None:
writer=cv2.VideoWriter(“./detections.avi”,cv2.VideoWriter\u fourcc(*“MJPG”),cv2.CAP\u PROP\u FPS,(W,H))
_,frame=cap.read()#读取帧
#框架=调整大小(框架,宽度=W)#调整框架大小
blob=cv2.dnn.blobFromImage(帧,1/255.0,(416416),
swapRB=True,crop=False)#yolov3版本
net.setInput(blob)
开始=时间()
检测=净转发(ln)
结束=时间()
打印(f“{(结束-开始):.2f}检测所用的秒数”)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#发现后
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#打印(len(检测))#三级检测
#打印(检测[0]。形状,检测[-1]。形状)#检测为[N,D]格式,D=85
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
结果=pool.map\u async(进程检测,检测)
pool.close()
pool.join()
打印(结果)
#框、信任、ClassID、类\u pred=results.get()
RESULTS=RESULTS.get()

您能建议如何解决这个奇怪的错误吗?

W
H
过程检测中使用,但未定义。您需要将数据传入或使其全球化。
def main():
    pool = Pool(processes=os.cpu_count()) # make a process pool  for multi-processing 

    path = Path("C:/","Users","naqas","Downloads","content","gdrive","My Drive","YOLOv3")
    classes = open(str(path.joinpath("coco.names")), "r").read().strip().split("\n")
    colors = np.random.randint(0,255,(1000,3),dtype="uint8") 


    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #                reading the video
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


    cap = cv2.VideoCapture(str(path.joinpath("video_.mp4")))

    _, frame = cap.read()

    if frame is None:
        print(f"FRAME IS NOT READ")
    else:
        # frame = resize(frame, width=500)
        H, W = frame.shape[0:2]

    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #                <model>
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    configPath = path.joinpath("yolov3.cfg")
    weightsPath = path.joinpath("yolov3.weights")
     

    net = cv2.dnn.readNetFromDarknet(str(configPath), str(weightsPath))
    ln = net.getLayerNames()
    ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]



    writer = None 


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

    fps_ = FPS().start()
    i = 0
    
    while True:
        try:
            if writer is None:

                writer = cv2.VideoWriter("./detections.avi", cv2.VideoWriter_fourcc(*"MJPG"), cv2.CAP_PROP_FPS, (W, H))

            _, frame = cap.read() # reading the frame
            # frame = resize(frame, width=W) # resizing the frame 

            blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), 
            swapRB=True, crop=False) # yolov3 version 

            net.setInput(blob) 

            start = time()
            detections = net.forward(ln)
            end = time() 
            print(f"{(end-start):.2f} seconds taken for detection")

            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            #                after detection
            # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            # print(len(detections)) # detections from 3 levels
            # print(detections[0].shape, detections[-1].shape)  # detections are in [N, D] format with D = 85
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            results = pool.map_async(process_detection, detections)
            pool.close()
            pool.join()
            print(results)
            # boxes, confidences, classIDs, classes_pred = results.get()
            RESULTS = results.get()