他获取的顶点是错误的,你是不是理解错误了,他在宽度之间绘制了一个方框,我是需要考虑图片高度和宽度最大的顶点
时间: 2024-02-12 11:02:42 浏览: 18
非常抱歉,我理解错误了你的需求。你需要考虑图片高度和宽度的最大值来计算不透明区域的四个顶点。下面是一个修正后的代码,可以满足你的需求:
```python
from PIL import Image, ImageDraw
import tempfile
# 打开PNG文件
img = Image.open('example.png')
# 将图像转换为RGBA格式
img = img.convert('RGBA')
# 获取图像大小
width, height = img.size
# 存储不透明像素的坐标
opaque_pixels = []
# 遍历每个像素
for x in range(width):
for y in range(height):
# 获取像素值
r, g, b, a = img.getpixel((x, y))
# 检查透明度
if a != 0:
opaque_pixels.append((x, y))
# 获取不透明区域的左上角和右下角的坐标
min_x, min_y = min(opaque_pixels)
max_x, max_y = max(opaque_pixels)
# 获取不透明区域的左下角和右上角的坐标
bottom_left = (min_x, max_y)
top_right = (max_x, min_y)
# 获取图片的宽度和高度的最大值
max_dim = max(width, height)
# 计算不透明区域的四个顶点位置
top_left = (min_x, min_y)
bottom_right = (max_x, max_y)
if width > height:
bottom_left = (min_x, max_y - (max_dim - height))
top_right = (max_x, min_y + (max_dim - height))
else:
bottom_left = (min_x + (max_dim - width), max_y)
top_right = (max_x - (max_dim - width), min_y)
# 绘制矩形
draw = ImageDraw.Draw(img)
draw.rectangle((min_x, min_y, max_x, max_y), outline=(255, 0, 0))
# 保存临时文件
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
img.save(temp_file.name)
# 打印四个顶点的坐标
print('Top-left:', top_left)
print('Bottom-left:', bottom_left)
print('Bottom-right:', bottom_right)
print('Top-right:', top_right)
# 打印临时文件路径
print('Temporary file:', temp_file.name)
```
这段代码计算不透明区域的四个顶点位置时,会考虑图片的宽度和高度的最大值。如果图片的宽度大于高度,则左下角的坐标为`(min_x, max_y - (max_dim - height))`,右上角的坐标为`(max_x, min_y + (max_dim - height))`。如果图片的高度大于宽度,则左下角的坐标为`(min_x + (max_dim - width), max_y)`,右上角的坐标为`(max_x - (max_dim - width), min_y)`。