python的opencv绝对路径读取图片
时间: 2023-10-06 16:07:04 浏览: 207
假设图片的绝对路径为`/home/user/image.jpg`,可以使用以下代码读取图片:
```python
import cv2
img = cv2.imread('/home/user/image.jpg')
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`cv2.imread()`函数用于读取图片,参数为图片的绝对路径。读取的图片可以通过`cv2.imshow()`函数显示在窗口中,然后通过`cv2.waitKey()`函数等待用户按下按键,最后通过`cv2.destroyAllWindows()`函数关闭窗口。
相关问题
opencv绝对路径读取图片
以下是使用OpenCV读取绝对路径下的图片的Python代码示例:
```python
import cv2
# 读取绝对路径下的图片
img = cv2.imread('/path/to/image.jpg', cv2.IMREAD_UNCHANGED)
# 显示图片
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`/path/to/image.jpg`为图片的绝对路径,`cv2.IMREAD_UNCHANGED`表示以原图形式读取图片。需要注意的是,路径内的斜杠一定为`/`或者`\\`。
python opencv 当前路径
### 当前路径下的 Python 和 OpenCV 操作
在 Python 中,可以使用 `os` 或 `pathlib` 库来获取当前工作目录的路径。结合 OpenCV 的功能,可以从该路径加载图像文件并显示它们。
#### 获取当前路径
以下是通过 `os.getcwd()` 方法获取当前工作目录的示例:
```python
import os
current_path = os.getcwd()
print(f"Current working directory: {current_path}")
```
此方法会返回程序运行时所在的目录路径[^1]。
#### 加载当前路径中的图像
假设当前路径下有一个名为 `example.jpg` 的图像文件,可以使用以下代码将其加载到内存中:
```python
import cv2
import os
# 获取当前路径
current_path = os.getcwd()
# 构造完整的图像路径
image_path = os.path.join(current_path, "example.jpg")
# 安全读取图像(解决中文路径问题)
def read_image_chinese(path):
try:
with open(path, "rb") as f:
return cv2.imdecode(np.frombuffer(f.read(), np.uint8), cv2.IMREAD_COLOR)
except Exception as e:
print(f"Error reading image: {str(e)}")
return None
img = read_image_chinese(image_path)
if img is not None:
# 显示图像
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("Failed to load the image.")
```
上述代码解决了可能存在的中文路径编码问题,并提供了更健壮的错误处理逻辑[^3]。
#### 列出当前路径下的所有图像文件
如果希望遍历当前路径下的所有图像文件,则可使用如下代码片段:
```python
import os
supported_extensions = ['.jpg', '.jpeg', '.png', '.bmp']
files_in_current_dir = [f for f in os.listdir(os.getcwd()) if any(f.lower().endswith(ext) for ext in supported_extensions)]
for file_name in files_in_current_dir:
full_path = os.path.join(os.getcwd(), file_name)
img = read_image_chinese(full_path)
if img is not None:
cv2.imshow(file_name, img)
cv2.waitKey(0)
cv2.destroyWindow(file_name)
```
这段代码能够自动检测支持的扩展名列表内的所有图像文件,并逐一展示出来[^2]。
---
阅读全文
相关推荐















