无法将网络图片转换为NumPy数组,请求技术协助
I've run into this exact error before! Let's break down why it's happening and how to fix it:
Why This Error Occurs
Most often, this happens because the PIL Image object you're working with is in a palette mode (like 'P') instead of a direct pixel mode (like 'RGB'). Numpy can't directly interpret palette-mapped image objects into integer arrays, hence the int() argument must be a string... not 'JpegImageFile' error. It can also pop up if you're using an outdated version of PIL (instead of the maintained Pillow fork).
Solution 1: Convert the Image to RGB Mode First
This is the simplest fix for palette-mode images. Converting to RGB ensures numpy can read the raw pixel values directly:
from PIL import Image from io import BytesIO import requests import numpy as np url = r'https://drive.google.com/uc?id=1xrKyFZAIIR_XVhlhYGHlfLvIr5vQ5EnW' response = requests.get(url) # Convert to RGB mode to avoid palette issues img = Image.open(BytesIO(response.content)).convert('RGB') arr = np.array(img, dtype=np.uint8)
Solution 2: Extract Pixel Data with getdata() and Reshape
If the first solution doesn't work, you can manually extract the pixel data and reshape it to match the image dimensions:
from PIL import Image from io import BytesIO import requests import numpy as np url = r'https://drive.google.com/uc?id=1xrKyFZAIIR_XVhlhYGHlfLvIr5vQ5EnW' response = requests.get(url) img = Image.open(BytesIO(response.content)) # Get raw pixel data and reshape to (height, width, channels) arr = np.array(img.getdata(), dtype=np.uint8).reshape(img.height, img.width, len(img.getbands()))
Quick Check: Verify Your Image Mode
To confirm the root cause, add a print statement to check the image's mode:
print(img.mode)
If the output is 'P', Solution 1 will definitely resolve the error.
Bonus: Update Pillow to the Latest Version
Old versions of PIL (not Pillow) have compatibility issues with numpy. Make sure you're using the maintained Pillow library:
pip uninstall PIL -y pip install --upgrade pillow
内容的提问来源于stack exchange,提问作者John

