[英]How to scale points within a bounding box to match another bounding box?
這是我正在研究的手寫識別算法。 我正在嘗試縮放點集,以便無論您寫的數字有多大或多小,它最終都會縮放到相同的大小。
我無法弄清楚如何做到這一點。 我的方法是這樣的。 我希望邊界框在內部縮放以在 x = (-256,256) 和 y = (-256,256) 定義的邊界框內完美匹配。 它應該拉伸和擠壓所有點,以便 4 個角匹配該大小。 所以我所做的是計算點之間的最大 x 距離,然后將其除以 512,這應該給出我需要多少縮放 x 軸上的每個點以匹配 -256、256 邊界。 對 y 軸重復該操作。 直覺上我認為它應該工作,但事實並非如此。
我該怎么做呢? 這在數學中叫什么,我想在這里完成什么?
這是我的 Python 代碼和我的嘗試。 pointsmod 應該有縮放點。
import matplotlib.pyplot as plt
import math
fig = plt.figure()
ax = fig.add_subplot()
points = [(73, 172), (3, 171), (-82, 170), (-130, 164), (-130, 103), (-130, 51), (-89, 80), (-35, 91), (16, 81), (57, 55), (71, 9), (65, -39), (36, -77), (-18, -85), (-65, -68), (-104, -32)]
def boundingbox(points):
x_min = min(point[0] for point in points)
x_max = max(point[0] for point in points)
y_min = min(point[1] for point in points)
y_max = max(point[1] for point in points)
return [(x_min, y_min), (x_min, y_max), (x_max, y_max), (x_max, y_min)]
bb = boundingbox(points)
def distance(point1, point2):
return math.sqrt((point1[0] - point2[0])**2+(point1[1] - point2[1])**2)
xlen = distance(bb[0], bb[3])
ylen = distance(bb[0],bb[1])
pointsmod = []
xfac = 512/xlen
yfac = 512/ylen
for point in points: # My attempt at scaling the points
x = point[0]*xfac
y = point[1]*yfac
pointsmod.append((x,y))
plt.xlim(-256, 256)
plt.ylim(-256, 256)
plt.scatter(*zip(*points))
plt.scatter(*zip(*pointsmod))
ax.set_aspect('equal')
plt.show()
好吧,你沒有考慮不同的起源。 您的邊界框不以 (0,0) 為中心。 說我們有
xmin = min(point[0] for point in points)
xmax = max(point[0] for point in points)
ymin = min(point[1] for point in points)
ymax = max(point[1] for point in points)
xlen = xmax - xmin
ylen = ymax - ymin
那么從points
框到 (-256,+256) 的翻譯是這樣的:
def scale( oldx, oldy ):
newx = (oldx - xmin) * 512 / xlen - 256
newy = (oldy - ymin) * 512 / ylen - 256
return newx, newy
將 (0,0) 移動到左上角,然后進行縮放,然后將原點移回中間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.