Как исправить застревание CMD после запуска кода python

#python #windows #command-prompt

#python #Windows #командная строка

Вопрос:

Итак … как сказано в названии, у меня есть скрипт на python, который в основном представляет собой yolo и находит номерной знак по заданному изображению. и он делает это правильно! отлично! но проблема в том, что недавно, когда я вызываю его, как обычно, из cmd, набрав ‘python yolo.py » он будет работать и выполнять ту работу, которую я хочу, но он застрял! и я вообще не могу ввести какую-либо другую команду. я должен закрыть cmd и запустить его снова. проблема в том, что этот скрипт предполагает вызов с другим скриптом, который является графическим интерфейсом, и при запуске yolo я больше не могу использовать программу и должен ее закрыть. и я выяснил, что этот скрипт без каких-либо изменений будет отлично работать на других компьютерах. кто-нибудь знает, как я могу это исправить?

 import numpy as np
import time
import cv2


INPUT_FILE= ('Outputs/original.jpg')
OUTPUT_FILE=('Outputs/_yolo.jpg')
LABELS_FILE='data/classes.names'
CONFIG_FILE='data/yolov3.cfg'
WEIGHTS_FILE='data/lapi.weights'
CONFIDENCE_THRESHOLD=0.3

LABELS = open(LABELS_FILE).read().strip().split("n")

np.random.seed(4)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),
    dtype="uint8")


net = cv2.dnn.readNetFromDarknet(CONFIG_FILE, WEIGHTS_FILE)

image = cv2.imread(INPUT_FILE)
(H, W) = image.shape[:2]

# determine only the *output* layer names that we need from YOLO
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))


# initialize our lists of detected bounding boxes, confidences, and
# class IDs, respectively
boxes = []
confidences = []
classIDs = []

# loop over each of the layer outputs
for output in layerOutputs:
    # loop over each of the detections
    for detection in output:
        # extract the class ID and confidence (i.e., probability) of
        # the current object detection
        scores = detection[5:]
        classID = np.argmax(scores)
        confidence = scores[classID]

        # filter out weak predictions by ensuring the detected
        # probability is greater than the minimum probability
        if confidence > CONFIDENCE_THRESHOLD:
            # scale the bounding box coordinates back relative to the
            # size of the image, keeping in mind that YOLO actually
            # returns the center (x, y)-coordinates of the bounding
            # box followed by the boxes' width and height
            box = detection[0:4] * np.array([W, H, W, H])
            (centerX, centerY, width, height) = box.astype("int")

            # use the center (x, y)-coordinates to derive the top and
            # and left corner of the bounding box
            x = int(centerX - (width / 2))
            y = int(centerY - (height / 2))

            # update our list of bounding box coordinates, confidences,
            # and class IDs
            boxes.append([x, y, int(width), int(height)])
            confidences.append(float(confidence))
            classIDs.append(classID)

# apply non-maxima suppression to suppress weak, overlapping bounding
# boxes
idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE_THRESHOLD,
    CONFIDENCE_THRESHOLD)

# ensure at least one detection exists
if len(idxs) > 0:
    # loop over the indexes we are keeping
    for i in idxs.flatten():
        # extract the bounding box coordinates
        (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]]]

        cv2.rectangle(image, (x, y), (x   w, y   h), color, 20)
        text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
        cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,
            0.5, color, 20)
# save the output image
ratio = 490.0 / image.shape[1]
dim = (490, int(image.shape[0] * ratio))
resized_img = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
cv2.imwrite(('Outputs/_yolo.jpg'), resized_img)

cropped_img = cv2.imread('Outputs/original.jpg')
cropped_img = cropped_img[y:y h, x:x w]
ratio = 490.0 / cropped_img.shape[1]
dim = (490, int(cropped_img.shape[0] * ratio))
resized_img = cv2.resize(cropped_img, dim, interpolation = cv2.INTER_AREA)
cv2.imwrite(('Outputs/license.jpg'), resized_img)
  

CMD выглядит так после завершения скрипта

1

Обновление: я добавляю threading.enumerate() в конце исходного скрипта, и результат был таким

2

Комментарии:

1. Да, я делал это раньше, и все идет нормально. как вы можете видеть, в конце скрипт напишет два изображения, сначала запустите его, напишите их, но поскольку он застрял в cmd, он не может выполняться дважды и более. если я добавлю print или что-нибудь еще в конце, также будет выполнено нормально, но оно снова застрянет после них. по сути, он застрял в нижней части скрипта после выполнения каждой отдельной строки кода.

2. tripleee, извините, английский не мой родной язык ‘-_-

3. Вы пытались выяснить, где программа застревает? Пожалуйста, имейте в виду, что использование print инструкций может быть неточным из-за проблем с очисткой буфера стандартного вывода.

4. не уверен, какую версию python вы используете, но вы можете попытаться threading.enumerate() проверить, нет ли застрявших / занятых потоков.

5. Карл Кнехтель, спасибо за ваш комментарий. да, я это сделал, при первом выполнении он будет запускать каждую строку, которая есть в скрипте, и застревает после них. все 107 строк кода будут выполняться, а затем застревают, если я добавлю больше строк, они тоже будут выполняться и снова застревают после них