使用 OpenCV Python 提取所有边界框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21104664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract all bounding boxes using OpenCV Python
提问by xandra12791
I have an image that contains more than one bounding box.
我有一张包含多个边界框的图像。
I need to extract everything that has bounding boxes in them. So far, from this site I've gotten this answer:
我需要提取其中包含边界框的所有内容。到目前为止,从这个网站我得到了这个答案:
y = img[by:by+bh, bx:bx+bw]
cv2.imwrite(string + '.png', y)
It works, however, it only gets one. How should I modify the code? I tried putting it in the loop for contours but it still spews out one image instead of multiple ones.
它有效,但是,它只有一个。我应该如何修改代码?我尝试将其放入轮廓循环中,但它仍然喷出一张图像而不是多张图像。
Thank you so much in advance.
非常感谢你。
采纳答案by Zaw Lin
there you go:
你去吧:
import cv2
im = cv2.imread('c:/data/ph.jpg')
gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
contours, hierarchy = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2:]
idx =0
for cnt in contours:
idx += 1
x,y,w,h = cv2.boundingRect(cnt)
roi=im[y:y+h,x:x+w]
cv2.imwrite(str(idx) + '.jpg', roi)
#cv2.rectangle(im,(x,y),(x+w,y+h),(200,0,0),2)
cv2.imshow('img',im)
cv2.waitKey(0)
回答by nathancy
A simple approach is to find all contours, obtain the bounding rectangle coordinates using cv2.boundingRectthen extract the ROI using Numpy slicing. We can keep a counter to save each ROI then save it with cv2.imwrite. Here's a working example:
一个简单的方法是找到所有轮廓,使用获取边界矩形坐标,cv2.boundingRect然后使用 Numpy 切片提取 ROI。我们可以保留一个计数器来保存每个 ROI,然后用cv2.imwrite. 这是一个工作示例:
Input image:
输入图像:
Detected ROIs to extract highlighted in green
检测到的 ROIs 以绿色突出显示
Saved ROIs
节省的投资回报率
Code
代码
import cv2
import numpy as np
# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.png')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Find contours, obtain bounding box, extract and save ROI
ROI_number = 0
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
ROI = original[y:y+h, x:x+w]
cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
ROI_number += 1
cv2.imshow('image', image)
cv2.waitKey()

