Несколько вызовов функций для параллельной обработки внутри цикла - PullRequest
0 голосов
/ 07 февраля 2020

I sh, чтобы обнаружить изображение с моей веб-камеры и записать результат, перемещается ли он влево или вправо, в файл. Чтобы увеличить частоту кадров (поскольку этот проект требует гораздо больше обработки и может быть запущен на Raspberry Pi), я решил выполнить запись файла с помощью многопроцессорной обработки (что я новичок):

код:

функция для многопроцессорной обработки

def send_cmd(cv):
    # ####EXECUTE LOGIC AND CREATE COMMAND###
# writing to file
# just a sample command// change as will
dictionary = {'left': 0, 'right': 0, 'stop': 0}

        if cv[0] == 'left':
            dictionary['right'] = 1
        else:
            dictionary['left'] = 1

cmd = '{"left":' + str(dictionary['left']) + ',"right":' + str(dictionary['left'
        ]) + ',"stop":' + str(dictionary['left']) + '}'
print("command written: " + cmd)
f = open('command.txt', 'w')
f.write(cmd)
f.close()

Основной код:

while True:
    try:
        frame = cv.VideoCapture(0)
        frame = imutils.resize(frame, width=400)

    if W is None or H is None:
        (H, W) = frame.shape[:2]

    blob = cv.dnn.blobFromImage(cv.resize(frame, (300, 300)),
                                0.007843, (300, 300), 127.5)
    net.setInput(blob)
    detections = net.forward()
    rects = []

    for i in range(0, detections.shape[2]):

        if detections[0, 0, i, 2] > args['confidence']:
            box = detections[0, 0, i, 3:7] * np.array([W, H, W, H])
            rects.append(box.astype('int'))

            (startX, startY, endX, endY) = box.astype('int')
            cv.rectangle(frame, (startX, startY), (endX, endY), (0,
                         0xFF, 0), 2)

    objects = ct.update(rects)

    for (objectID, centroid) in objects.items():

        text = 'ID {}'.format(objectID)
        cv.putText(
            frame,
            text,
            (centroid[0] - 10, centroid[1] - 10),
            cv.FONT_HERSHEY_SIMPLEX,
            0.5,
            (0, 0xFF, 0),
            2,
            )
        cv.circle(frame, (centroid[0], centroid[1]), 4, (0, 0xFF,
                  0), -1)
        center = (centroid[0], centroid[1])
        pts.appendleft(center)

        for i in np.arange(1, len(pts)):

            if pts[i - 1] is None or pts[i] is None:
                continue

            if counter >= 10 and i == 1 and pts[-1] is not None:
                dX = pts[-1][0] - pts[i][0]
                dY = pts[-1][1] - pts[i][1]
                global dirX
                global dirY
                (dirX, dirY) = ('', '')

                if np.abs(dX) > 20:
                    dirX = ('left' if np.sign(dX) == 1 else 'right')

                if np.abs(dY) > 20:
                    dirY = ('up' if np.sign(dY) == 1 else 'down')

                #tried multiprocessing with process method but to many process calls at the same time
                order = multiprocessing.Process(target = send_cmd,args = ([dirX, dirY]))
                order.start()
                order.join()

                # send_cmd(cv=[dirX, dirY], us=ultra_sonic)


                if dirX != '' and dirY != '':
                    direction = '{}-{}'.format(dirY, dirX)
                else:

                    direction = (dirX if dirX != '' else dirY)

            thickness = int(np.sqrt(args['buffer'] / float(i + 1))
                            * 2.5)

        cv.putText(
            frame,
            direction,
            (10, 30),
            cv.FONT_HERSHEY_SIMPLEX,
            0.65,
            (0, 0, 0xFF),
            3,
            )
        cv.putText(
            frame,
            'dx: {}, dy: {}'.format(dX, dY),
            (10, frame.shape[0] - 10),
            cv.FONT_HERSHEY_SIMPLEX,
            0.35,
            (0, 0, 0xFF),
            1,
            )

    cv.imshow('Frame', frame)
    key = cv.waitKey(1) & 0xFF
    counter += 1

Ошибка:

 RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

Может ли кто-нибудь помочь мне?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...