python - 类型错误 : only size-1 arrays can be converted to Python scalars (matplotlib)

标签 python arrays matplotlib

#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from random import random

#Show Images
image_show = True

#Parameters ( mm )
square_size = 50
room_width = 5000
room_length = 10000
n_guess = 50 # number of random points generated
max_cell_value = 255 # highest number in a cell.

#Handy functions for conversions
def mm2grid( mm):
    return int(mm/square_size)
def grid2mm( grid):
    return int(grid*square_size)
def rotation( theta):
    return np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])

# Build a simple empty map
map_floor = np.zeros((mm2grid(room_width), mm2grid(room_length)),)
# NOTE: Any cell >0 is considered occupied

print("Map size= {} cells".format( map_floor.shape))

# Set border walls
map_floor[ 0, :] = 255
map_floor[-1, :] = 255
map_floor[ :, 0] = 255
map_floor[ :,-1] = 255

#Draw something in the centre
map_floor[20:80,100:120] = 100

### Target Position ###
target = np.array([2500,0])

### Robot Position ###
x = np.array([1000,1000, np.pi*0])

# Randomly generate n_number of positions #
x_rand = np.zeros(( 3, n_guess))
for k in range( n_guess):
    x_rand[:,k] = np.array([ random()*room_width, random()* room_length, random()*3.14159]) 
    #remove any points inside a solid object
    if map_floor[ int(mm2grid( x_rand[0,k])), int(mm2grid( x_rand[1,k]))] > 0:
        x_rand[:,k] = 0

### TODO ###
#for n_number calculate angle to target#
#for n_number calculate distance measurement to nearest wall.

#### Display Map ####
# Remember: images are printed y inverted and x first.
if image_show:
    # Draw Map
    plt.matshow( max_cell_value-map_floor, cmap=plt.cm.gray) # max_cell_value is just to correct color scheme
    # Draw randomly positioned squares on the map
    plt.plot( [mm2grid( x_rand[1,:])], [mm2grid(x_rand[0,:])],'rx')
    # Draw Robot position
    plt.plot( [mm2grid( x[1])], [mm2grid(x[0])], 'b8', markersize=12)
    plt.plot( [mm2grid( x[1]), mm2grid( x[1]+ 300*np.cos(x[2]))],\
              [mm2grid( x[0]), mm2grid( x[0]+ 300*np.sin(x[2]))], 'b-', linewidth=2.5)
    plt.text( mm2grid( x[1]), mm2grid( x[0]+300), 'Robot', color='b')
    # Draw target
    plt.plot( [mm2grid( target[1])],[mm2grid( target[0])], 'g>', markersize=30)
    plt.text( mm2grid( target[1]), mm2grid( target[0] - 250), 'Target', color='g')
    # Draw line from robot to target
    plt.plot( [mm2grid( x[1]), mm2grid(target[1])],\
              [mm2grid( x[0]), mm2grid(target[0])], 'k--')
    # Show everything.
    plt.show()

我不知道如何修复该错误。 在第 48 行中,我将 xrange 更改为 range 我还对其他一些地方做了一些其他操作来修复和错误,我在第 26 行中遇到了错误,它说

TypeError: 'float' object cannot be interpreted as an index

但看起来我已经解决了这些问题,但我不确定我是否在某个地方弄乱了某些东西,现在它给了我这个错误:

Map size= (100, 200) cells
Traceback (most recent call last):
  File "/Users/oscarwallace/Downloads/Map.py", line 64, in <module>
    plt.plot( [mm2grid( x_rand[1,:])], [mm2grid(x_rand[0,:])],'rx')
  File "/Users/oscarwallace/Downloads/Map.py", line 19, in mm2grid
    return int(mm/square_size)
TypeError: only size-1 arrays can be converted to Python scalars

我想知道是否有人知道我必须做什么才能阻止这种情况发生。提前致谢。

最佳答案

当您尝试将不仅仅是一个标量的东西转换为整数时,会发生此错误。例如,一个包含两个元素的 ndarray 。这是此错误的示例:

import numpy as np

int(np.array([1, 3]))

TypeError: only size-1 arrays can be converted to Python scalars

你可以做的是使用.astype(int)

(mm/square_size).astype(int)

关于python - 类型错误 : only size-1 arrays can be converted to Python scalars (matplotlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60271558/

相关文章:

java - 使用同步块(synchronized block)的锁

ios - 将 UIPickerView 视为组合/选择框

java - 获取数组中 'X'位置的位数

python - ValueError : Failed to find font DejaVu Sans:style=normal:variant=normal:weight=normal. ..并且回退到默认字体被禁用

python - 如何自定义散点矩阵以查看所有标题?

python - 如何将带有日期的文本写入 JSON 文件而不对其进行序列化

python - Django + Testypie 问题 : AppRegistryNotReadyException

python - 使用 Nginx throttle 服务器脚本

python - Python 中将列表元素嵌套到数据框

python - 如何将手动自定义的 seaborn 图添加到 JointGrid/jointplot