How to slice image by broadcasting slices? Error: 'only integer scalar arrays can be converted to a scalar index' in python?
How to slice image by broadcasting slices? Error: 'only integer scalar arrays can be converted to a scalar index' in python?
我有一个简单的任务:
我有一张图片和一系列点。对于每个点,我都想从图像中切出框。
我可以在 for 循环中执行此操作,但对于数千个点来说它非常慢,因此我需要在没有循环的情况下执行此操作。我正在尝试将数组广播到切片值。下面是一些说明问题的最小代码:
import numpy as np
frame = cv2.imread("input.png")
pts = np.array([[10,20],
[30,40],
[50,60]]) #and thousands more
x1s = pts[:, 0]
y1s = pts[:, 1]
x2s = x1s + 5
y2s = y1s + 5
cutouts = frame[x1s:x2s,y1s:y2s]
这给了我错误:
TypeError: only integer scalar arrays can be converted to a scalar index
为什么?切片都是一维整数数组(标量)。这应该工作。哪里出了问题,我该如何正确处理?
关于此错误的其他 Whosebug 帖子似乎与切片或广播无关。
编辑:明确一点,点数组将有数千个点。我想要一个包含数千个 5x5 切片的数组,每个点一个。所以一个切片从 (10,20) 开始,另一个切片从 (30,40) 开始,等等
Edit2:人们说你不能在二维数组上广播。然而 this 有效,这是相同的概念。为什么?
import numpy as np
import cv2
frame = np.arange(50).reshape(5,10)
pts1 = np.array([1,2,3])
pts2 = np.array([4,5,6])
cutouts = frame[pts1,pts2]
print cutouts
#outputs [14 25 36]
pts[:, 0]的形状是(2,),所以不是标量
试试这个,它应该对你的情况有帮助。
imgfrag = img[pts[0,0]:pts[1,0], pts[0,1]:pts[1,1]]
答:不可以。 Numpy 不允许这样做。
我有一个简单的任务: 我有一张图片和一系列点。对于每个点,我都想从图像中切出框。
我可以在 for 循环中执行此操作,但对于数千个点来说它非常慢,因此我需要在没有循环的情况下执行此操作。我正在尝试将数组广播到切片值。下面是一些说明问题的最小代码:
import numpy as np
frame = cv2.imread("input.png")
pts = np.array([[10,20],
[30,40],
[50,60]]) #and thousands more
x1s = pts[:, 0]
y1s = pts[:, 1]
x2s = x1s + 5
y2s = y1s + 5
cutouts = frame[x1s:x2s,y1s:y2s]
这给了我错误:
TypeError: only integer scalar arrays can be converted to a scalar index
为什么?切片都是一维整数数组(标量)。这应该工作。哪里出了问题,我该如何正确处理?
关于此错误的其他 Whosebug 帖子似乎与切片或广播无关。
编辑:明确一点,点数组将有数千个点。我想要一个包含数千个 5x5 切片的数组,每个点一个。所以一个切片从 (10,20) 开始,另一个切片从 (30,40) 开始,等等
Edit2:人们说你不能在二维数组上广播。然而 this 有效,这是相同的概念。为什么?
import numpy as np
import cv2
frame = np.arange(50).reshape(5,10)
pts1 = np.array([1,2,3])
pts2 = np.array([4,5,6])
cutouts = frame[pts1,pts2]
print cutouts
#outputs [14 25 36]
pts[:, 0]的形状是(2,),所以不是标量 试试这个,它应该对你的情况有帮助。
imgfrag = img[pts[0,0]:pts[1,0], pts[0,1]:pts[1,1]]
答:不可以。 Numpy 不允许这样做。