gpt4 book ai didi

Python OpenCV 调整大小(插值)

转载 作者:太空宇宙 更新时间:2023-11-03 21:41:24 25 4
gpt4 key购买 nike

我正在调整图像 init_input 的大小以及该图像中目标对象 g 的边界框以执行对象定位。我目前正在通过确定有多少像素将被上采样并将其中的一半添加到每个边界框坐标来调整边界框的大小。

我的代码如下:

def next_state(init_input, b_prime, g):
"""
Returns the observable region of the next state.

Formats the next state's observable region, defined
by b_prime, to be of dimension (224, 224, 3). Adding 16
additional pixels of context around the original bounding box.
The ground truth box must be reformatted according to the
new observable region.

:param init_input:
The initial input volume of the current episode.

:param b_prime:
The subsequent state's bounding box. RED

:param g:
The ground truth box of the target object. YELLOW
"""

# Determine the pixel coordinates of the observable region for the following state
context_pixels = 16
x1 = max(b_prime[0] - context_pixels, 0)
y1 = max(b_prime[1] - context_pixels, 0)
x2 = min(b_prime[2] + context_pixels, IMG_SIZE)
y2 = min(b_prime[3] + context_pixels, IMG_SIZE)

# Determine observable region
observable_region = cv2.resize(init_input[y1:y2, x1:x2], (224, 224))

# Difference between crop region and image dimensions
x1_diff = x1
y1_diff = y1
x2_diff = IMG_SIZE - x2
y2_diff = IMG_SIZE - y2

# Resize ground truth box
g[0] = int(g[0] - 0.5 * x1_diff) # x1
g[1] = int(g[1] - 0.5 * y1_diff) # y1
g[2] = int(g[2] + 0.5 * x2_diff) # x2
g[3] = int(g[3] + 0.5 * y2_diff) # y2

return observable_region, g

我遇到的问题是这种方法不准确。如下例所示,边界框仍然处于关闭状态。我的想法是,这是由于在调整图像大小时插值的工作方式所致(因此所拍摄的像素之间存在偏差,不是 0.5)。任何有关如何解决此问题的建议将不胜感激。

Example

感谢 lenik 的工作示例

Working

最佳答案

基本上,最好在两个维度上均等缩放,以防止圆形和方形被压扁。所以首先,你必须找到规模。为此,您可以找到最大尺寸的边界框并添加 32(两侧各 16 像素),因此:

longest = max( x_size, y_size) + 32
scale = 224.0 / longest

然后通过计算边界框的中心并在所有方向上添加最长的一半来找到角点:

center_x = (x1 + x2) / 2
center_y = (y1 + y2) / 2

org_x1 = center_x - longest/2
org_x2 = center_x + longest/2

org_y1 = center_y - longest/2
org_y2 = center_y + longest/2

然后您将坐标为 (org_x1, org_y1, org_x2, org_y2) 的矩形重新缩放为 (224,224) 矩形,您的边界框的角将从图像角偏移 16.0 * scale


好的,据我所知,您将 init_input[y1:y2, x1:x2] 的大小调整为 (224,224) 并想知道,ground truth 区域在哪里将。好吧,原来地面实况矩形距离角点 16 个像素,所以你必须找到这些新的偏移量,你就完成了。

x_offset = 16.0 * 224.0 / (x2-x1)
y_offset = 16.0 * 224.0 / (y2-y1)

那么地面实况矩形将在 (x_offset, y_offset) 的左上角和在 ((224 - x_offset), (224 - y_offset)) 的右下角

您可以忽略我在除法器上方编写的其余代码,它是在假设您保留 x/y 比率的前提下编写的,而您没有 =)


这是弄清楚你在做什么的第三次尝试...如果你将 init_input[y1:y2, x1:x2] 缩放为 (224,224),变换后任意随机点(x,y)的坐标可以计算为:

x_new = (x - x1) * 224.0 / (x2 - x1)
y_new = (y - y1) * 224.0 / (y2 - y1)

根据图像大小最小化/最大化新值可能是个好主意,这样您就不会脱离图像边界:

x_new = max( 0, min( 224, x_new))
y_new = max( 0, min( 224, y_new))

关于Python OpenCV 调整大小(插值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51229202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com