繁体   English   中英

提取边界框并将其保存为图像

[英]Extract bounding box and save it as an image

假设您有以下图像:

例子:

现在我想将每个独立的字母提取到单独的图像中。 目前,我已经恢复了轮廓,然后绘制了一个边界框,在本例中为字符a

字符“a”的边界框

在此之后,我想提取每个框(在本例中为字母a )并将其保存到图像文件中。

预期结果:

结果

到目前为止,这是我的代码:

import numpy as np
import cv2

im = cv2.imread('abcd.png')
im[im == 255] = 1
im[im == 0] = 255
im[im == 1] = 0
im2 = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(im2,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for i in range(0, len(contours)):
    if (i % 2 == 0):
       cnt = contours[i]
       #mask = np.zeros(im2.shape,np.uint8)
       #cv2.drawContours(mask,[cnt],0,255,-1)
       x,y,w,h = cv2.boundingRect(cnt)
       cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
       cv2.imshow('Features', im)
       cv2.imwrite(str(i)+'.png', im)

cv2.destroyAllWindows()

提前致谢。

下面会给你一封信

letter = im[y:y+h,x:x+w]

这是一种方法:

  • 将图像转换为灰度
  • 获得二值图像的 Otsu 阈值
  • 寻找轮廓
  • 使用 Numpy 切片遍历轮廓并提取 ROI

找到轮廓后,我们使用cv2.boundingRect()来获取每个字母的边界矩形坐标。

x,y,w,h = cv2.boundingRect(c)

为了提取 ROI,我们使用 Numpy 切片

ROI = image[y:y+h, x:x+w]

由于我们有边界矩形坐标,我们可以绘制绿色边界框

cv2.rectangle(copy,(x,y),(x+w,y+h),(36,255,12),2)

这是检测到的字母

在此处输入图像描述

这是每个保存的字母 ROI

在此处输入图像描述

import cv2

image = cv2.imread('1.png')
copy = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]

cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

ROI_number = 0
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    ROI = image[y:y+h, x:x+w]
    cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
    cv2.rectangle(copy,(x,y),(x+w,y+h),(36,255,12),2)
    ROI_number += 1

cv2.imshow('thresh', thresh)
cv2.imshow('copy', copy)
cv2.waitKey()
        def bounding_box_img(img,bbox):
            x_min, y_min, x_max, y_max = bbox
            bbox_obj = img[y_min:y_max, x_min:x_max]
            return bbox_obj

        img = cv2.imread("image.jpg")
        cropped_img = bounding_box_img(img,bbox)
        cv2.imshow(cropped_img)

这将返回裁剪图像(边界框)

在这种方法中,边界框坐标基于 pascal-voc 注释格式,如这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM