You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中设置图像指定区域的像素强度为零

Python实现TIFF图像指定区域像素置零的解决方案

下面提供两种常用的Python实现方案,可根据你的需求选择:

方法一:使用Pillow + NumPy

Pillow是Python常用的图像处理库,结合NumPy可以方便地对图像像素进行批量操作。

  1. 先安装依赖库:
pip install pillow numpy
  1. 示例代码:
from PIL import Image
import numpy as np

# 读取TIFF图像
img = Image.open("your_image.tif")
# 转换为NumPy数组(便于像素级操作)
img_array = np.array(img)

# --- 矩形区域置零 ---
# 定义区域范围:[起始行, 结束行),[起始列, 结束列)
start_row, end_row = 50, 200
start_col, end_col = 100, 300
# 将指定区域像素设为0
img_array[start_row:end_row, start_col:end_col] = 0

# --- 不规则区域(如圆形)置零(可选)---
# x0, y0为圆心坐标,r为半径
# x0, y0, r = 150, 125, 50
# rows, cols = img_array.shape
# y, x = np.ogrid[:rows, :cols]
# distance = np.sqrt((x - x0)**2 + (y - y0)**2)
# img_array[distance <= r] = 0

# 转换回图像对象并保存
processed_img = Image.fromarray(img_array)
processed_img.save("processed_image.tif")

方法二:使用OpenCV + NumPy

OpenCV在计算机视觉场景中应用广泛,适合处理复杂图像操作。

  1. 安装依赖库:
pip install opencv-python numpy
  1. 示例代码:
import cv2
import numpy as np

# 读取TIFF图像(IMREAD_UNCHANGED保留原图像的位深度)
img = cv2.imread("your_image.tif", cv2.IMREAD_UNCHANGED)

# --- 矩形区域置零 ---
start_row, end_row = 50, 200
start_col, end_col = 100, 300
img[start_row:end_row, start_col:end_col] = 0

# --- 不规则区域(如圆形)置零(可选)---
# x0, y0为圆心坐标,r为半径
# x0, y0, r = 150, 125, 50
# mask = np.zeros(img.shape[:2], dtype=np.uint8)
# cv2.circle(mask, (x0, y0), r, 255, -1)  # 创建圆形掩码
# img[mask == 255] = 0

# 保存处理后的图像
cv2.imwrite("processed_image.tif", img)

注意事项

  • 替换代码中的your_image.tif为你的实际图像路径
  • 可通过img.size(Pillow)或img.shape(OpenCV/NumPy)查看图像尺寸,确保定义的区域范围在图像边界内
  • 多通道TIFF(如RGB)同样适用,代码会将对应区域的所有通道像素置零

内容的提问来源于stack exchange,提问作者Anna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:06:08