简体   繁体   中英

python+openCV : only size-1 arrays can be converted to Python scalars

This is my code to rotate the img with cv2.getRotationMatrix2D() function.

smoothed_angle = 0

img = cv2.imread("/home/hp/self driving car/steering_wheel_image.png")
print(img.shape) #outputs (240, 240, 3)
rows = img.shape[0]
print(rows) #outputs 240
cols = img.shape[1]
print(cols) #outputs 240

M = cv2.getRotationMatrix2D((cols/2,rows/2),-smoothed_angle,1)

I am getting the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-37-55419a87d5b5> in <module>()
     34 #and the predicted angle
     35 smoothed_angle += 0.2 * pow(abs((predicted_angle_degree - smoothed_angle)), 2.0 / 3.0) * (predicted_angle_degree - smoothed_angle) / abs(predicted_angle_degree - smoothed_angle)
---> 36 M = cv2.getRotationMatrix2D((cols/2,rows/2),-smoothed_angle,1)
     37 dst = cv2.warpAffine(img,M,(cols,rows))
     38 #cv2.imshow("steering wheel", dst)

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

Also, print(type(smoothed_angle)) gives the following output:

<class 'numpy.ndarray'>

The example script doesn't return an error as it is written. But in your error output, there's a line 35 that says:

     35 smoothed_angle += 0.2 * pow(abs((predicted_angle_degree - smoothed_angle)), 2.0 / 3.0) * (predicted_angle_degree - smoothed_angle) / abs(predicted_angle_degree - smoothed_angle)

This isn't in the example script, but might be a source of the problem (or another step that isn't in the example). If you start with smoothed_angle = 0 but predicted_angle_degree is an array instead of a scalar (eg predicted_angle_degree = np.array([0,0]) ), it will result in the error shown. So it looks to be that the error is due to smoothed_angle not being a scalar.

Update with the type info : As shown with the type for smoothed_angle , it's not a scalar or it would have printed <type 'int'> or <type 'float'> . If smoothed_angle did start as a scalar like in the example, then it's being changed by another function not given in the example, like the one in line 35. This would also mean that another parameter that's being used to update smoothed_angle , such as predicted_angle_degree , also has type ndarray .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM