0

I'm trying to detect objects in an image in python using YoloV4 and Darknet. The problem is that it isn't detecting any objects in the image. This is my code:

configPath = "./cfg/yolov4.cfg"                                 
weightPath = "./yolov4.weights"                                 
metaPath = "./cfg/coco.data"

netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1)
metaMain = darknet.load_meta(metaPath.encode("ascii"))
altNames = None
try:
    with open(metaPath) as metaFH:
        metaContents = metaFH.read()
        import re
        match = re.search("names *= *(.*)$", metaContents, re.IGNORECASE | re.MULTILINE)
        if match:
            result = match.group(1)
        else:
            result = None
        try:
            if os.path.exists(result):
                with open(result) as namesFH:
                     namesList = namesFH.read().strip().split("\n")
                     altNames = [x.strip() for x in namesList]
        except TypeError:
            pass
except Exception:
    pass

frame_width = darknet.network_width(netMain)
frame_height = darknet.network_height(netMain)

frame = cv2.imread("b.jpg")

darknet_image = darknet.make_image(frame_width, frame_height, 3)
darknet.copy_image_from_bytes(darknet_image, frame.tobytes())
detections = darknet.detect_image(netMain, metaMain, darknet_image, thresh=0.25)
print(detections) #returns []

The program prints "[]". The image ("b.jpg") is 764x756.

1 Answers1

0

You need to resize the image with proper size.

frame = cv2.resize(cv2.imread("b.jpg"), (frame_width, frame_height))

Make sure, the image has the objects you're looking for.

Before using the python script, use the darknet test to ensure the model can detect objects.

Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60
  • I tested the image with darknet test from cmd and it recognized two persons, so the image has the objects. I also tried resizing the image with your code but this time nothing happens, it never returns from darknet.detect_image() – Francisco Linan Feb 28 '21 at 06:50
  • In that case, can you try with the updated API from AlexeyAB repo? Or, you can try with this model server https://github.com/zabir-nabil/darknet-fastapi-modelserver – Zabir Al Nazi Feb 28 '21 at 07:13
  • What do you mean by the updated API? I'm using darknet from AlexeyAB (I compiled it myself) and I tried the cmd command "darknet.exe detector test cfg/coco.data cfg/yolov4.cfg yolov4.weights ", it works fine. – Francisco Linan Feb 28 '21 at 19:00