【问题标题】:Get multiple images crops from single image从单个图像中获取多个图像裁剪
【发布时间】:2021-10-18 13:15:27
【问题描述】:

我正在开发一个 OCR,它扫描检测器模块检测到的文本,假设一个图像具有 n 边界框,我想要一个读取 .xml 的函数,该函数获取坐标以裁剪边界框周围的图像.这是我尝试过的:

def get_cropped_image(image_file, 
                  images_path = "data/split/train/images",
                  annotations_path = "data/split/train/annotations"):

    images_filenames = os.listdir(images_path)
    annotations_filenames = os.listdir(annotations_path)

    image = cv2.imread(os.path.join(images_path, image_file))
    annotation_filename = image_file.split(sep='.')[0]+'.xml'


    bboxes, labels = read_annotation_file(annotations_path, annotation_filename)

    for idx, label in enumerate(labels):
        try:
            cropped_img = imcrop(image, bboxes[idx]).copy()
            return cropped_img
        except:
            raise

但是,此函数仅返回每个图像的第一个边界框裁剪。我怎样才能真正从每张图片中返回 n 作物?

【问题讨论】:

  • 您是否考虑过将裁剪后的子图像放入列表中,然后将其返回?这很简单,如果您已经编写了该代码,您应该不会感到惊讶
  • 确实,我已经将它们放入一个列表并尝试使用字典将 image_id(键)映射到 numpy 数组。但是,我想知道这是否是 最好的 方法(我想尽量减少内存使用)。
  • 您在帖子中没有说任何这些,所以我倾向于相信您在此处提出建议之前没有想到这一点。

标签: python opencv computer-vision


【解决方案1】:

您可以返回裁剪图像的列表:

imgList = []

for idx, label in enumerate(labels):
    imgList.append(imcrop(image, bboxes[idx]).copy())

return imgList

【讨论】:

  • 如果您的问题实际上是为了解决有关内存消耗的问题,那么您应该指出这一点。如果您将return 语句更改为yield,那么它将成为一个生成器并在每次调用时返回一个作物。在这里阅读...realpython.com/introduction-to-python-generators
猜你喜欢
  • 1970-01-01
  • 2011-09-03
  • 2019-01-19
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多