【问题标题】:Extract all bounding boxes using OpenCV Python使用 OpenCV Python 提取所有边界框
【发布时间】:2014-02-01 23:43:14
【问题描述】:

我的图片包含多个边界框。

我需要提取其中包含边界框的所有内容。到目前为止,从这个网站我得到了这个答案:

y = img[by:by+bh, bx:bx+bw]
cv2.imwrite(string + '.png', y)

它有效,但是,它只得到一个。我应该如何修改代码?我尝试将其放入轮廓循环中,但它仍然会喷出一张图像而不是多张图像。

非常感谢您。

【问题讨论】:

    标签: python opencv image-processing computer-vision extract


    【解决方案1】:

    一个简单的方法是find contours,使用cv2.boundingRect()获取边界矩形坐标 然后使用 Numpy 切片提取 ROI。我们可以保留一个计数器来保存每个 ROI,然后用cv2.imwrite() 保存它。这是一个工作示例:

    输入图片:

    检测到的 ROI 以绿色突出显示

    保存的投资回报率

    代码

    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()
    

    【讨论】:

      【解决方案2】:

      你去吧:

      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)    
      

      【讨论】:

      • 如果上面的代码出现以下错误,ValueError: too many values to unpack (expected 2),更改以下行:contours,hierarchy, _ = cv2.findContours(gray,cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
      • 请修复您的代码中的错误,即使我遇到与上述相同的错误
      猜你喜欢
      • 2018-10-06
      • 2021-10-20
      • 2019-06-12
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2015-07-13
      相关资源
      最近更新 更多