我正在使用python为我的计算摄影课做作业。该方法需要str2
,我不知道该怎么做。我试过numpy.int64
,但它给了我一个未定义的全局名称。我不知道该怎么做。我得到的错误是numpy.astype(int64)
。
ValueError: Error - x_locs values have type <type 'numpy.ndarray'>. Expected value type is <type 'numpy.int64'>
这是测试方法的代码,如果有帮助的话。
def getYXLocations(image, intensity_value):
""" This function gets the Y, X locations of an image at a certain intensity
value.
It's easy to describe how to do this visually. Imagine you have a grayscale
image that is 4x4.
my_image = [ [ 17, 200, 48, 10],
[ 98, 151, 41, 182],
[128, 190, 98, 209],
[249, 27, 129, 182]]
Now assume I ask you to return getYXLocations(my_image, 98)
You have to return the y and x locations of where 98 appears, so in this
case, 98 appears at 1, 0 and at 2, 2, so your function should return
y_locs = [1, 2] and x_locs = [0, 2].
Hint: There is a numpy function that will essentially allow you to do this
efficiently & succintly. May be worth looking into ;).
The less efficient but equally valid way of doing this:
1. Iterate through the rows (y) and columns (x) of the image.
2. if image[y, x] == intensity_value, append y to y_locs and x to x_locs.
3. return y_locs, x_locs.
Args:
image (numpy.ndarray): Input grayscale image.
intensity_value (numpy.uint8): Assume a value from 0->255.
Returns:
y_locs (numpy.ndarray): Array containing integer values for the y
locations of input intensity. Type np.int64.
x_locs (numpy.ndarray): Array containing integer values for the x
locations of input intensity. Type np.int64.
"""
# WRITE YOUR CODE HERE.
# dim of the image
dim = image.shape
# axis
xax = dim[1]
yax = dim[0]
count = 0
# loopings for count
for x in range (0, xax):
for y in range (0, yax):
if image[x][y] == intensity_value:
count = count + 1
# creates x loc and y loc
x_locs = np.empty([1, count], dtype=np.int64)
y_locs = np.empty([1, count], dtype=np.int64)
# loops for location
place = 0
for x in range (0, xax):
for y in range (0, yax):
if image[x][y] == intensity_value:
x_locs[0][place] = x
y_locs[0][place] = y
place = place + 1
print np.array_str(x_locs)
print np.array_str(y_locs)
# x_locs = x_locs.astype(int64)
# y_locs = y_locs.astype(int64)
return x_locs, y_locs
# END OF FUNCTION
答案 0 :(得分:1)
我认为这个问题来自于此检查 -
if type(x_locs[0]) != type(x_ans[0]):
raise ValueError(
("Error - x_locs values have type {}." +
" Expected value type is {}.").format(type(x_locs[0]),
type(x_ans[0])))
正如您在test_answers
中看到的那样,x_ans[0]
的类型为np.int64
,因为x_ans是一维数组。
但是当你在另一个函数中创建x_locs
时,你将它创建为一个2D数组,形状为(1,10),因此当你访问x_locs[0]
时,你得到一个阵列。
可能适合您的一些解决方案 -
您正在定义x_locs
和y_locs
,其中只有一个数组(其中有count
个元素),也许您应该将它们定义为1D数组而不是2D数组(我可以看到,在你的测试函数中,你在假设它们是一维数组的情况下进行了大量的测试,但实际上并非如此)。要将它们更改为1D数组,请将以下行更改为 -
x_locs = np.empty([count], dtype=np.int64)
y_locs = np.empty([count], dtype=np.int64)
请注意,在您尝试访问阵列后,您应该使用x_locs[place]
,而不是x_locs[0][place]
。
另一种解决方案是纠正您的测试逻辑,将x_locs
和y_locs
作为2D数组处理,而不是一维数组。