使用 Python Mahotas 加载图像


Python 以其强大的库而闻名,这些库几乎可以处理任何任务,图像处理也不例外。为此,一个受欢迎的选择是 Mahotas,一个计算机视觉和图像处理库。本文探讨了如何使用 Python 的 Mahotas 加载图像,并提供了实际示例。

Mahotas 简介

Mahotas 是一个复杂的库,包含许多用于图像处理和计算机视觉的方法。Mahotas 非常注重速度和效率,使您可以使用 100 多个功能,包括颜色空间转换、滤波、形态学、特征提取等等。本指南重点介绍图像处理中最基本的一个阶段——加载图像。

安装 Mahotas

在开始加载照片之前,我们必须首先确认 Mahotas 是否已安装。您可以使用 pip 将此包添加到您的 Python 环境中

pip install mahotas

确保您拥有最新版本,以获得最佳性能并访问所有功能。

使用 Mahotas 加载图像

mahotas.imread() 函数读取图像并将其加载到 NumPy 数组中。它支持多种文件格式,包括 JPEG、PNG 和 TIFF。

示例 1:基本图像加载

加载图像就像向 imread() 函数提供图像路径一样简单

import mahotas as mh

# Load the image
image = mh.imread('path_to_image.jpg')

# Print the type and dimensions of the image
print(type(image))
print(image.shape)

此代码加载图像并输出尺寸(高度、宽度和颜色通道数)、类型(应该是 numpy ndarray)和图像的类型。

示例 2:灰度图像加载

在某些情况下,您可能希望立即将图像加载为灰度。为此,您可以使用 as_grey 参数

import mahotas as mh

# Load the image as grayscale
image = mh.imread('path_to_image.jpg', as_grey=True)

# Print the type and dimensions of the image
print(type(image))
print(image.shape)

由于只有一个颜色通道,因此图像现在是一个二维数组(仅有高度和宽度)。

示例 3:从 URL 加载图像

Mahotas 允许直接从 URL 加载图像。Imread() 无法直接执行此功能,因此我们必须使用其他库,如 urllib 和 io

import mahotas as mh
import urllib.request
from io import BytesIO

# URL of the image
url = 'https://example.com/path_to_image.jpg'

# Open URL and load image
with urllib.request.urlopen(url) as url:
   s = url.read()

# Convert to BytesIO object and read image
image = mh.imread(BytesIO(s))

# Print the type and dimensions of the image
print(type(image))
print(image.shape)

借助此代码,您可以快速将网络上的图像加载到 numpy ndarray 中,以便进一步处理。

结论

图像处理的第一步是加载图像,而 Python 的 Mahotas 包使此过程变得简单。无论您是在处理本地文件还是网络照片,彩色还是灰度,Mahotas 都能为您提供所需的工具。

通过熟练掌握图像加载,您已经在掌握 Python 的图像处理能力方面取得了进步。然而,旅程并没有到此结束;Mahotas 拥有丰富的工具可供您进一步修改和分析您的照片。

更新于: 2023-07-18

149 次查看

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.