[Python] How do I train an object detection model using Torchvision's pre-trained models?

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    I read the torchvision API documentation using pre-trained models for object detection. This is an example they have included:

    from torchvision.io.image import decode_image
    from torchvision.models.detection import fasterrcnn_resnet50_fpn_v2, FasterRCNN_ResNet50_FPN_V2_Weights
    from torchvision.utils import draw_bounding_boxes
    from torchvision.transforms.functional import to_pil_image

    img = decode_image("test/assets/encode_jpeg/grace_hopper_517x606.jpg")

    # Step 1: Initialize model with the best available weights
    weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT
    model = fasterrcnn_resnet50_fpn_v2(weights=weights, box_score_thresh=0.9)
    model.eval()

    # Step 2: Initialize the inference transforms
    preprocess = weights.transforms()

    # Step 3: Apply inference preprocessing transforms
    batch = [preprocess(img)]

    # Step 4: Use the model and visualize the prediction
    prediction = model(batch)[0]
    labels = [weights.meta["categories"] for i in prediction["labels"]]
    box = draw_bounding_boxes(img, boxes=prediction["boxes"],
    labels=labels,
    colors="red",
    width=4, font_size=30)
    im = to_pil_image(box.detach())
    im.show()


    Based on this line:

    img = decode_image("test/assets/encode_jpeg/grace_hopper_517x606.jpg")


    the model is using only one image. Is there a way I can customize this so that I can train this model on several images?

    Continue reading...

Compartilhe esta Página