[英]Crop multiple bounding boxes from image with list of bounding boxes
使用 Amazon 的 Rekognition,我使用以下內容從 JSON 響應中提取了感興趣的邊界框:
def __init__(self, image):
self.shape = image.shape
def bounding_box_convert(self, bounding_box):
xmin = int(bounding_box['Left'] * self.shape[1])
xmax = xmin + int(bounding_box['Width'] * self.shape[1])
ymin = int(bounding_box['Top'] * self.shape[0])
ymax = ymin + int(bounding_box['Height'] * self.shape[0])
return (xmin,ymin,xmax,ymax)
def polygon_convert(self, polygon):
pts = []
for p in polygon:
x = int(p['X'] * self.shape[1])
y = int(p['Y'] * self.shape[0])
pts.append( [x,y] )
return pts
def get_bounding_boxes(jsondata):
objectnames = ('Helmet','Hardhat')
bboxes = []
a = jsondata
if('Labels' in a):
for label in a['Labels']:
#-- skip over anything that isn't hardhat,helmet
if(label['Name'] in objectnames):
print('extracting {}'.format(label['Name']))
lbl = "{}: {:0.1f}%".format(label['Name'], label['Confidence'])
print(lbl)
for instance in label['Instances']:
coords = tmp.bounding_box_convert(instance['BoundingBox'])
bboxes.append(coords)
return bboxes
if __name__=='__main__':
imagefile = 'image011.jpg'
bgr_image = cv2.imread(imagefile)
tmp = Tmp(bgr_image)
jsonname = 'json_000'
fin = open(jsonname, 'r')
jsondata = json.load(fin)
bb = get_bounding_boxes(jsondata)
print(bb)
輸出是一個邊界框列表:
[(865, 731, 1077, 906), (1874, 646, 2117, 824)]
我可以輕松地從列表中提取一個位置並使用以下方法另存為新圖像:
from PIL import Image
img = Image.open("image011.jpg")
area = (865, 731, 1077, 906)
cropped_img = img.crop(area)
cropped_img.save("cropped.jpg")
但是,我還沒有找到使用“bb”列表輸出從圖像中裁剪和保存多個邊界框的好的解決方案。
我確實在這里找到了從 csv 中提取信息的解決方案: 在 1 張圖像中裁剪多個邊界框的最有效/最快捷的方法,超過數千張圖像? .
但是,我相信有一種比將邊界框數據保存到 csv 並重新讀入更有效的方法。
我不太擅長編寫自己的函數 - 非常感謝所有建議!
假設你的邊界框坐標是x,y,w,h
的形式x,y,w,h
你可以做ROI = image[y:y+h,x:x+w]
來裁剪。 使用此輸入圖像:
使用如何獲得 ROI Bounding Box Coordinates without Guess & Check 中的腳本來獲取x,y,w,h
邊界框坐標來裁剪這些 ROI:
我們簡單地遍歷邊界框列表並使用 Numpy 切片對其進行裁剪。 提取的投資回報率:
這是一個最小的例子:
import cv2
import numpy as np
image = cv2.imread('1.png')
bounding_boxes = [(17, 24, 47, 47),
(74, 28, 47, 50),
(125, 15, 51, 61),
(184, 18, 53, 53),
(247, 25, 44, 46),
(296, 6, 65, 66)
]
num = 0
for box in bounding_boxes:
x,y,w,h = box
ROI = image[y:y+h, x:x+w]
cv2.imwrite('ROI_{}.png'.format(num), ROI)
num += 1
cv2.imshow('ROI', ROI)
cv2.waitKey()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.