Skip to content
Advertisement

Unable to use subprocess in my colab python code

as part of a project I am doing wity Yolov4, I am trying to test multiple images with learned weights and copy the resulting images with added bounding boxes to my google drive. The following is the code I am running on colab. It just isn’t working, and there is no log messages to debug. Please not if I run the command in the cmd variable directly, it is working fine, but that’s just for one image. My aim is to automate or “batch” the testing process.

Thanks for your help.

    #%%capture
    import os,sys
    import subprocess
    directory = '/content/darknet/data/testimages/'
        for filename in os.listdir(directory):
            #cmd = "./darknet detector test data/obj.data cfg/yolov4-obj.cfg /content/darknet/cfg/yolov4-obj_4000.weights /content/darknet/data/testimages/" + filename 
            cmd = "!./darknet detector test data/obj.data cfg/yolov4-obj.cfg /content/darknet/cfg/yolov4-obj_4000.weights /content/darknet/data/testimages/" + filename 
            try:
              subprocess.run([sys.executable,cmd])
            except:
              print("failed")
            #print(os.path.join(directory, filename))
            cmd = "!cp 'predictions.jpg' '/mydrive/birds/results/" + filename + "_results.jpg' "
            #print(cmd)
            #cmd = "ls -ltr"
            subprocess.run([sys.executable,cmd])

Advertisement

Answer

After a few hours of trial and error, a simple documentation search on Colab’s page gave me the answer. It was under the heading “passing values to and from the shell”. The following modified code does the trick for me.

%%capture
import os,sys
import subprocess
directory = '/content/darknet/data/testimages/'
for filename in os.listdir(directory):
    cmd =  "./darknet detector test data/obj.data cfg/yolov4-obj.cfg /content/darknet/cfg/yolov4-obj_4000.weights /content/darknet/data/testimages/" + filename
    try:
      !{cmd}
    except:
      print("failed")
    cmd = "cp 'predictions.jpg' '/mydrive/birds/results/" + filename + "_results.jpg' "
    !{cmd}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement