在 Ubuntu 上使用 Python 进行图像处理的快速指南
一 环境准备
python3 --version、pip3 --versionsudo apt update && sudo apt install -y python3-pippython3 -m venv venv && source venv/bin/activatepip install pillowpip install opencv-pythonpip install scikit-image二 使用 Pillow 进行基础编辑
pip install pillowfrom PIL import Image, ImageEnhance
# 1) 打开与显示
img = Image.open('example.jpg')
# 2) 转为灰度并缩放
gray = img.convert('L')
resized = gray.resize((400, 400))
# 3) 增强对比度
enhancer = ImageEnhance.Contrast(resized)
enhanced = enhancer.enhance(1.5)
# 4) 保存
enhanced.save('example_gray_resized_enhanced.jpg', quality=95)
三 使用 OpenCV 进行计算机视觉处理
pip install opencv-pythonimport cv2
# 1) 读取(BGR 顺序)
img = cv2.imread('example.jpg')
# 2) 转为灰度
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 3) 边缘检测(Canny)
edges = cv2.Canny(gray, threshold1=100, threshold2=200)
# 4) 保存
cv2.imwrite('edges.jpg', edges)
# 5) 需要显示时(有图形环境)
# cv2.imshow('Edges', edges)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
四 常见问题与实用建议
Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)opencv-python-headless 避免 GUI 依赖;或用 matplotlib 显示图像(plt.imshow())。ImageFont.truetype 时提供绝对路径,避免 “cannot open resource” 错误。