簡體   English   中英

使用 cv2 調整圖像大小后,如何獲取新的邊界框坐標

[英]After resizing an image with cv2, how to get the new bounding box coordinate

我有一個大小為 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)),我如何獲得新邊界框的坐標?

您可以通過簡單地使用調整大小操作的比例來做到這一點。 像這樣——

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 )

回答:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM