【问题标题】:After resizing an image with cv2, how to get the new bounding box coordinate用cv2调整图像大小后,如何获取新的边界框坐标
【发布时间】:2016-12-03 22:44:48
【问题描述】:

我有一个尺寸为 720 x 1280 的图像,我可以像这样将其调整为 256 x 256

import cv2
img = cv2.imread('sample_img.jpg')
img_small = cv2.resize(img, (256, 256), interpolation=cv2.INTER_CUBIC)

假设我在原始图像中有一个边界框(左上角(50, 100),右下角(350, 300)),如何获取新边界框的坐标?

【问题讨论】:

  • 通过 x, width 和 y, height 分别乘以 x,y 中的缩放因子

标签: python opencv computer-vision


【解决方案1】:

您可以通过简单地使用调整大小操作的比例来做到这一点。像这样——

import numpy as np

# Get the scaling factor
# img_shape = (y, x)
# reshaped_img_shape = (y1, x1)
# the scaling factor = (y1/y, x1/x)
scale = np.flipud(np.divide(reshaped_img_shape, img_shape))  # you have to flip because the image.shape is (y,x) but your corner points are (x,y)

#use this on to get new top left corner and bottom right corner coordinates
new_top_left_corner = np.multiply(top_left_corner, scale )
new_bottom_right_corner = np.multiply(bottom_right_corner, scale )

【讨论】:

  • 缩放因子 = (y1/y, x1/x),这是一个 min 函数吗?比如 min(y1/y, x1/x) ?
【解决方案2】:

答案:

new_x_coordinate = x_coordinate/(original_x_length/new_x_length)
new_y_coordinate = y_coordinate/(original_y_length/new_y_length)

完整代码:

import numpy as np

def new_coordinates_after_resize_img(original_size, new_size, original_coordinate):
  original_size = np.array(original_size)
  new_size = np.array(new_size)
  original_coordinate = np.array(original_coordinate)
  xy = original_coordinate/(original_size/new_size)
  x, y = int(xy[0]), int(xy[1])
  return (x, y)

output = new_coordinates_after_resize_img((1080,720), (244,244), (102, 34)) # just modify this line
print(output) # output: (23, 11)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-10
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    相关资源
    最近更新 更多