crop objects from jpg based on label file

import os
import cv2


for i in os.listdir("./labels"):
    label_file = os.path.join("./labels",i)
    img = cv2.imread("./crop_night/" + i.replace(".txt",".jpg"))
    #print("./crop_night/" + i.replace(".txt",".jpg"))
    with open(label_file, "r") as j:
         num = 1
         for line in j:
             car = line.strip()
             print(car)
             x1 = eval(car.split(" ")[4])
             y1 = eval(car.split(" ")[5])
             x2 = eval(car.split(" ")[6])
             y2 = eval(car.split(" ")[7])
             x1 = int(x1)
             y1 = int(y1)
             x2 = int(x2)
             y2 = int(y2)
             cropped = img[ y1 : y2, x1 : x2 ]
             print(x1,y1,x2,y2)
             print("./result/" + str(i.split(".")[0]) + "_" + str(num) + ".jpg")
             cv2.imwrite("./result/" + str(i.split(".")[0]) + "_" + str(num) + ".jpg",  cropped)
             num = num + 1

  

posted on 2021-01-27 18:05  cdekelon  阅读(47)  评论(0编辑  收藏  举报

导航