Why do I get "TypeError: expected np.ndarray (got numpy.ndarray)" when I use torch.from_numpy() function?

Why do I get “TypeError: expected np.ndarray (got numpy.ndarray)” when I use torch.from_numpy() function? Isn’t np.ndarray equivalent to numpy.ndarray? Also, there doesn’t seem to be any np.ndarray type, but only numpy.ndarray type.

Traceback (most recent call last): File "test_opencv.py", line 31, in <module> bounding_boxes, landmarks = detect_faces(img, pnet, rnet, onet) File "/home/xxx/git/project/src/detector.py", line 67, in detect_faces boxes = run_first_stage(image, pnet, scale=s, threshold=thresholds[0]) File "/home/xxx/git/project/src/first_stage.py", line 73, in run_first_stage img = torch.from_numpy(img).unsqueeze(0).permute(0,3,1,2).cuda().float() TypeError: expected np.ndarray (got numpy.ndarray)

Can you share some debugging info like printing type(img) and img.dtype I wrote the same line of code and it worked for me.
There has to be some bug in the data loading process of the image.

Hello It seems you are getting the error because the argument to from_numpy function is a single value rather than array.
In numpy, there is difference between np.array(1) and np.array([1]) and both are completely different data types.
Try torch.from_numpy(np.asarray(x)).

3 Likes

Hello, I have encountered the same problem. Do you have any solutions?Thank you

Try
torch.as_tensor(np.array(pil_img).astype('float'))

It worked for me.

1 Like

Have you fix this problem? I encounter this problem too…

Could you post a minimal code snippet to reproduce this error?

I found it is because of the version of numpy…




信工 刘蓬博

邮箱:pengbo18555@163.com

签名由 网易邮箱大师 定制

It’s also happening to me on numpy 1.17.4, my own solution is to downgrade to 1.16.4

thanks! it worked for me.
Numpy version - 1.19.5

It worked for me. Thank you @raghavendragaleppa