gpt4 book ai didi

python - 如何将图像裁剪、调整大小表示为仿射变换?

转载 作者:行者123 更新时间:2023-12-01 05:01:05 25 4
gpt4 key购买 nike

我有一个图像被裁剪并调整为图像输入大小。
据我了解,这与仿射变换相同。

我试图简化下面的代码,因此它通过使用函数来做同样的事情:(类似于下面的例子)。

scipy.ndimage.affine_transform() 

问题是我不太了解该函数的参数,因此我无法使用 affine_transform() 函数实现优雅的单行。
提供和解释代码的解决方案可能有助于我更好地理解这个 affine_transform() 函数。
import numpy as npy
import PIL.Image
import scipy.misc as smc
import scipy.ndimage as snd

#crop factor
s = 1.045

#input image
img2crop = npy.float32(PIL.Image.open("input_image.jpg)")
h, w = img2crop.shape[:2] #get the dimensions of the input image

#Box-crop values: calculate new crop Dimensions based on 's'
wcrop = float(w) / (s)
hcrop = float(wcrop) / (float(w) / float(h))
hcrop = int(round(hcrop))
wcrop = int(round(wcrop))

#crop applied from top-left to right and bottom
b_left = 0
b_top = 0
b_width = wcrop
b_height = hcrop
b_box = (b_left, b_top, b_width, b_height)

#cropped region
region = img2crop.crop(b_box)

#resize cropped region back to input size
resized_region = smc.imresize(region, (h, w), interp='nearest', mode=None)
#save cropped and resized region as new file in output folder
PIL.Image.fromarray(np.uint8(resized_newregion)).save("output_image.jpg")

题:
上面进行裁剪和调整大小的代码如何表示为仿射变换?

此示例在所有 4 个边上均匀裁剪,居中
s = 0.0065
cropped_and_resized_image = snd.affine_transform(input_image.jpg, [1-s,1-s,1], [h*s/2,w*s/2,0], order=1)
PIL.Image.fromarray(npy.uint8(cropped_and_resized_image)).save("output_image_at.jpg")

提前感谢您的反馈。

最佳答案

这是 OpenCV 实现

# OpenCV implementation of crop/resize using affine transform

import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
import cv2

src_rgb = cv2.imread('test_img.jpg')

# Source width and height in pixels
src_w_px = 640
src_h_px = 480

# Target width and height in pixels
res_w_px = 640
res_h_px = 480

# Scaling parameter
s = 2.0

Affine_Mat_w = [s, 0, res_w_px/2.0 - s*src_w_px/2.0]
Affine_Mat_h = [0, s, res_h_px/2.0 - s*src_h_px/2.0]

M = np.c_[ Affine_Mat_w, Affine_Mat_h].T
res = cv2.warpAffine(src_rgb, M, (res_w_px, res_h_px))

# Showing the result
plt.figure(figsize=(15,6))
plt.subplot(121); plt.imshow(src_rgb); plt.title('Original image');
plt.subplot(122); plt.imshow(res); plt.title('Image warped Affine transform');

关于python - 如何将图像裁剪、调整大小表示为仿射变换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32619184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com