python 图像_python根据数据生成图像

python 图像_python根据数据生成图像在 Python 中 处理图像数据可以通过多种库实现 以下是一些常用的方法和库 1 使用 PIL Python Imaging Library 或 Pillow 库 打开和显示图像 pythonfrom PIL import Imageimg Image open example jpg img show 调整图像大小 pythonimg resized img

在Python中,处理图像数据可以通过多种库实现,以下是一些常用的方法和库:

1. 使用PIL(Python Imaging Library)或Pillow库

打开和显示图像

python

from PIL import Image

img = Image.open('example.jpg')

img.show()

调整图像大小

python

img_resized = img.resize((100, 100))

img_resized.save('resized_example.jpg')

转换图像格式

python

img.save('example.png')

图像滤镜处理

python

from PIL import ImageFilter

img_filtered = img.filter(ImageFilter.BLUR)

img_filtered.show()

图像旋转

python

img_rotated = img.rotate(90)

img_rotated.show()

图像裁剪

python

img_cropped = img.crop((100, 100, 200, 200))

img_cropped.show()

获取图像的像素数据

python

rgb_im = img.convert('RGB')

r, g, b = rgb_im.getpixel((1, 1))

2. 使用OpenCV库

读取图像

python

import cv2

raw_image = cv2.imread('panda.jpg')

图像大小调整

python

image_resize = cv2.resize(raw_image, (128, 128))

图像保存

python

cv2.imwrite('new_panda.jpg', image_resize)

图像格式转换(BGR到RGB)

python

image_rgb = cv2.cvtColor(raw_image, cv2.COLOR_BGR2RGB)

3. 使用Matplotlib库

读取图像

python

import matplotlib.pyplot as plt

image = plt.imread('image.jpg')

图像大小调整

python

image_resize = plt.resize((128, 128))

图像保存

python

plt.imwrite('new_image.jpg', image_resize)

4. 使用NumPy库

图像读取

python

import numpy as np

image_array = np.array(image_resize)

图像保存

python

image_output = Image.fromarray(image_array)

image_output.save('image_output.jpg')

5. 使用requests和BeautifulSoup库抓取网页上的图片数据

python

import requests

from bs4 import BeautifulSoup

url = 'https://example.com'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

img_tags = soup.find_all('img')

for img_tag in img_tags:

img_url = img_tag['src']

img_data = requests.get(img_url).content

with open('path/to/save/image.jpg', 'wb') as f:

f.write(img_data)

以上方法可以根据具体需求选择适合的方法进行使用。需要注意的是,Pillow是PIL库的升级版,提供了更多的图像处理功能。

编程小号
上一篇 2026-03-17 08:16
下一篇 2026-03-17 08:12

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/72627.html