python - 如何根据坐标框裁剪图像的特定部分?
问题描述
我想根据检测到的对象的坐标框裁剪我的图像,即 classID=1 的对象。
可能有多个具有相同 id 或其他类的对象。我的问题是我的代码只返回一个裁剪图像,我如何返回 ClassID=1 的所有裁剪图像?
我总共有 6 个类,我对 ClassID=1 感兴趣。
# initializing bounding boxes, confidences, and classIDs.
boxes = []
confidences = []
classIDs = []
for output in layersOutputs:
# loop over each of the detections
for detection in output:
# extract the class ID and confidence
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
# filter out weak predictions
if confidence > c_threshold:
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
#coordinates
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
# update bounding box coordinates, confidences, classIDs
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
# applying non maximum suppression
ind = cv.dnn.NMSBoxes(boxes, confidences, c_threshold, nms)
if len(ind) > 0:
# loop over the indexes that we want to keep
for i in ind.flatten():
# extract the bounding box coordinates
(x, y) = (boxes[1][0], boxes[1][1])
(w, h) = (boxes[1][2], boxes[1][3])
for i in classIDs:
if i != 1:
continue
# extract the bounding box coordinates
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
# crop that part of image which contains desired object
image = image[y:y + h, x:x + w]
cv.imshow("Image", image)
path = '/path to folder'
cv.imwrite(os.path.join(path, 'PImage.jpg'), image)
#
cv.waitKey(0)
编辑:你可以看到这张照片中有很多类型的动物,我正在尝试裁剪其中有狗的图像的一部分。我已经得到了与狗部分相关的坐标边界框(这意味着我知道其中有狗的矩形的位置在哪里,如图所示)
我想裁剪我在图像中指示的那些矩形。狗的类 id=1。我有类 cat 和其他具有不同索引的动物。
解决方案
你的循环不正确。
classID= [1]
for i in classID:
在这里,您基本上会说for i in [1]:
,哪些作物仅用于您的第一次检测。相反,您应该遍历所有检测。假设您的代码的其余部分是正确的,以下循环遍历所有登录的检测classID
,并且仅在它属于类 1 时才进行裁剪。
for i in classID:
if i!=1:
continue
推荐阅读
- angular - 拖放以在启用了分页和排序的垫表上工作
- c# - 如何使用 StringAsEnumResolver 在 ASP.NET Core 5 OData 中按字符串过滤枚举?
- paypal - PayPal - Native Checkout SDK(Android) - 无效范围
- reactjs - 需要刷新页面更新状态并在reactjs中显示
- c# - 具有匹配角色的用户登录时不显示 AuthorizeView 元素的内容
- html - HTML 背景颜色:是否可以从 div 填充屏幕?
- canvas - 40.000 个具有不同裁剪的相同纹理实例 – 仅 35 fps
- python-3.x - 将 Rasa 连接到数据库以存储响应
- excel - VBA getElementsByTagName() 只返回 102 行
- node.js - 巢穴。ValidationPipe 不处理复合对象