def __make_power_2(img, base, method=Image.BICUBIC): ow, oh = tuple(img.size) h = int(round(oh / base) * base) w = int(round(ow / base) * base) if (h == oh) and (w == ow): return img return img.resize((w, h), method) 这个函数怎么按照你刚才说的修改?
时间: 2024-04-08 21:34:02 浏览: 13
对于你提供的代码,我注意到你已经正确地将 `img.size` 转换为元组。因此,不需要对该部分进行修改。但是,为了避免 `round()` 函数返回整数而不是浮点数的问题,可以使用 `math.ceil()` 来确保得到正确的舍入值。
以下是修改后的代码:
```python
import math
def __make_power_2(img, base, method=Image.BICUBIC):
ow, oh = tuple(img.size)
h = int(math.ceil(oh / base) * base)
w = int(math.ceil(ow / base) * base)
if (h == oh) and (w == ow):
return img
return img.resize((w, h), method)
```
现在,`h` 和 `w` 的计算将使用 `math.ceil()` 来确保得到正确的舍入值。这样,你就可以避免整数解包和舍入错误的问题。请根据你的代码逻辑进行相应的修改。
相关问题
resample=resImg.BICUBIC AttributeError: 'numpy.ndarray' object has no attribute 'BICUBIC'
这个错误是因为你正在尝试在一个numpy数组上使用Image.BICUBIC方法,但是这个方法只能在Image对象上使用。你需要将你的numpy数组转换为Image对象,然后再使用BICUBIC方法。你可以使用以下代码将numpy数组转换为Image对象:
img = Image.fromarray(numpy_array)
然后你可以使用以下代码在Image对象上使用BICUBIC方法:
resized_img = img.resize((new_width, new_height), resample=Image.BICUBIC)
from PIL import Image, ImageDraw # 将图片平移并旋转 gray2 = Image.fromarray(src) width, height = gray2.size # 计算中心点和X轴角度 center = (max_point[0], max_point[1]) angle = np.arctan2(point2[1] - max_point[1], point2[0] - max_point[0]) * 180 / np.pi img_translated = gray2.transform((width, height), Image.AFFINE, (1, 0, center[0] - width/2, 0, 1, center[1] - height/2), resample=Image.BICUBIC) img_translated_rotated = img_translated.rotate(angle, resample=Image.BICUBIC, expand=True)from PIL import Image, ImageDraw #裁剪 img4 = Image.fromarray(src) width1, height1 = img4.size width2, height2 = img_translated_rotated.size left = (width2 - width1 )/2 top = (height2 - height1 )/2 right = (width2 - width1 )/2 + width1 bottom = (height2 - height1 )/2 + height1 cropped_image = img_translated_rotated.crop((left, top, right, bottom )) 现在已知在旋转前的图片gray2上有对应的点集合points,对点集points进行平移和旋转变换,使得其能在旋转后图片上完全重合的代码
可以参考以下代码:
```python
from PIL import Image, ImageDraw
import numpy as np
# 原始图片
gray2 = Image.fromarray(src)
# 中心点和旋转角度
max_point = (100, 100) # 假设最大点为(100, 100)
point2 = (200, 200) # 假设另一个点为(200, 200)
center = (max_point[0], max_point[1])
angle = np.arctan2(point2[1] - max_point[1], point2[0] - max_point[0]) * 180 / np.pi
# 平移和旋转变换
width, height = gray2.size
img_translated = gray2.transform((width, height), Image.AFFINE, (1, 0, center[0] - width/2, 0, 1, center[1] - height/2), resample=Image.BICUBIC)
img_translated_rotated = img_translated.rotate(angle, resample=Image.BICUBIC, expand=True)
# 裁剪
width1, height1 = gray2.size
width2, height2 = img_translated_rotated.size
left = (width2 - width1 )/2
top = (height2 - height1 )/2
right = (width2 - width1 )/2 + width1
bottom = (height2 - height1 )/2 + height1
cropped_image = img_translated_rotated.crop((left, top, right, bottom))
```
其中,假设最大点为(100, 100)、另一个点为(200, 200),可以根据实际情况修改。