將yolov3識別的目標,分割為小圖保存


大圖切割為小圖(這個博主的鏈接我實在找不到了,各位朋友如有發現一定告訴我,定加上轉載)

import os
import cv2 as cv
import argparse
import numpy as np
import cv2
weightsPath="F:/Python/ModelArts/yolov3.weights"
configPath="F:/Python/ModelArts/darknet-master/cfg/yolov3.cfg"
labelsPath="F:/Python/ModelArts/darknet-master/data/coco.names"
rootdir = r"F:\Python\ModelArts\test1/frames1"   #圖像讀取地址
savepath = "F:/Python/ModelArts/image/output/test2"  # 圖像保存地址

#初始化一些參數
LABELS = open(labelsPath).read().strip().split("\n")  #物體類別
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),dtype="uint8")#顏色


filelist = os.listdir(rootdir)  # 打開對應的文件夾
total_num = len(filelist)  #得到文件夾中圖像的個數
print(total_num)
# 如果輸出的文件夾不存在,創建即可
if not os.path.isdir(savepath):
    os.makedirs(savepath)

for(dirpath,dirnames,filenames) in os.walk(rootdir):

    for filename in filenames:

    # 必須將boxes在遍歷新的圖片后初始化
        boxes = []
        confidences = []
        classIDs = []
        net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
        path = os.path.join(dirpath,filename)
        #print(path)
        image = cv.imread(path)
        #print(image)
        (H, W) = image.shape[:2]
    # 得到 YOLO需要的輸出層
        ln = net.getLayerNames()
        ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
        #從輸入圖像構造一個blob,然后通過加載的模型,給我們提供邊界框和相關概率
        blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416),swapRB=True, crop=False)
        net.setInput(blob)
        layerOutputs = net.forward(ln)
        #在每層輸出上循環
        for output in layerOutputs:
            # 對每個檢測進行循環
            for detection in output:

                scores = detection[5:]

                classID = np.argmax(scores)
                confidence = scores[classID]

                #過濾掉那些置信度較小的檢測結果
                if confidence > 0.9:
                    #框后接框的寬度和高度
                    box = detection[0:4] * np.array([W, H, W, H])
                    (centerX, centerY, width, height) = box.astype("int")
                    #邊框的左上角
                    x = int(centerX - (width / 2))
                    y = int(centerY - (height / 2))
                    # 更新檢測出來的框
                   # 批量檢測圖片注意此處的boxes在每一次遍歷的時候要初始化,否則檢測出來的圖像框會疊加
                    boxes.append([x, y, int(width), int(height)])
                    #print(boxes)
                    confidences.append(float(confidence))
                    #print(confidences)
                    classIDs.append(classID)
        print('boxes:',boxes)
        print('confidences:',confidences)
        print(type(boxes),type(confidences))
        # 極大值抑制
        idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5,0.3)
        k = -1
        if len(idxs) > 0:
            # for k in range(0,len(boxes)):
            for i in idxs.flatten() :
                (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]]]
                # image是原圖,     左上點坐標, 右下點坐標, 顏色, 畫線的寬度
                cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
                text = "{}: {:.3f}".format(LABELS[classIDs[i]], confidences[i])
                print('type:',LABELS[classIDs[i]])
                savepath = "F:/Python/ModelArts/image/output/test2"  # 圖像保存地址
                savepath=savepath+'/'+LABELS[classIDs[i]]
                # 如果輸出的文件夾不存在,創建即可
                if not os.path.isdir(savepath):
                    os.makedirs(savepath)
                # 各參數依次是:圖片,添加的文字,左上角坐標(整數),字體,        字體大小,顏色,字體粗細
                cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5, color, 2)
                # 圖像裁剪注意坐標要一一對應
                # 圖片裁剪 裁剪區域【Ly:Ry,Lx:Rx】
                cut = image[y:(y+h), x:(x + w)]
                #print(type(cut))
                if cut.size != 0:
            # boxes的長度即為識別出來的車輛個數,利用boxes的長度來定義裁剪后車輛的路徑名稱
                    if k < len(boxes):
                        k = k+1
                   # 從字母a開始每次+1
                    t = chr(ord("a")+k)
                    
                    print(filename)
                    print(filename.split(".")[0]+"_"+t+".jpg")
                    cv2.imwrite(savepath+"/"+filename.split(".")[0]+"_"+t+".jpg",cut)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM