我正在try 读取一个图像:test_Image.png(如下面的屏幕截图所示).

我try 了各种组合--但都不能正确使用.

(在屏幕截图-docs-jupyter源文件中,我的以下python代码就是在这里编写的)

from PIL import Image
import numpy as np

filename = r"C:\Users\First.lastname\OneDrive - CompanyName Inc\Workspace\PythonWorkspace\test_image.png"
img1 = np.array(Image.open(filename))

错误:FileNotFoundError:没有这样的文件或目录:

Screenshot of my file and location

我如何读取文件?我使用的是Windows10,使用的是Python Python3.

我一直在寻找解决这个问题的办法,但似乎行不通.我也try 过不使用"r",使用"/"而不是"",还有"\"等(在阅读了Stackoverflow上类似问题的答案后)

"我的道路已经".和""(空格)--这会引起问题吗?

我还try 删除整个路径,只使用与我的.ipynb相同的文件夹中的"test_Image.png"-仍然得到相同的错误.

推荐答案

试试看吧.

import numpy as np
from PIL import Image

def read_image(filename):
  """Reads an image file and converts it to a NumPy array.

  Args:
    filename: The path to the image file.

  Returns:
    A NumPy array containing the pixel data for the image.
  """

  image = Image.open(filename)
  image_array = np.array(image)
  return image_array

# Get the absolute path to the test image file.
filename = "C:\\Users\\First.lastname\\OneDrive - CompanyName Inc\\Workspace\\PythonWorkspace\\test_image.png"

# Read the image file and convert it to a NumPy array.
image_array = read_image(filename)

# Do something with the image array.
# For example, you could display the image:
# import matplotlib.pyplot as plt
# plt.imshow(image_array)
# plt.show()

# Or, you could save the image to a new file:
# new_filename = "new_image.png"
# Image.fromarray(image_array).save(new_filename)

print("Image successfully read and converted to NumPy array.")

Python相关问答推荐

网页抓取数据框架但只有500个字节

为什么判断pd.DataFrame的值与判断pd.Series的值存在差异(如果索引中有值)?

带有计数值的Pandas数据帧

Python在通过Inbox调用时给出不同的响应

使用Curses for Python保存和恢复终端窗口内容

在Transformer中使用LabelEncoding的ML模型管道

Tkinter -控制调色板的位置

如何终止带有队列的Python进程?+ 队列大小的错误?

在上下文管理器中更改异常类型

从包含数字和单词的文件中读取和获取数据集

如何用symy更新分段函数

计算所有前面行(当前行)中列的值

Python:在类对象内的字典中更改所有键的索引,而不是仅更改一个键

Python daskValue错误:无法识别的区块管理器dask -必须是以下之一:[]

使可滚动框架在tkinter环境中看起来自然

如何在UserSerializer中添加显式字段?

Scrapy和Great Expectations(great_expectations)—不合作

Polars asof在下一个可用日期加入

将scipy. sparse矩阵直接保存为常规txt文件

Flask Jinja2如果语句总是计算为false&