python - 使用 Python 在保持比例的同时调整图像大小
问题描述
我有一个关于使用 python 预处理一些图像的问题。我发现的大多数答案都使用 Java,我需要使用 Python。
我有一个包含 2050 张图像的训练集,我想将它们的大小调整为 224 x 224,以便稍后将它们提供给卷积神经网络 (CNN)。最大的问题是我不能在不丢失图像比例的情况下做到这一点。并非所有图像的大小都相同。例如,我有 1000 x 700 像素和 700 x 600 像素的图像。
我的想法是使用周围像素的平均值用像素填充图像的较小一侧。但我真的不知道如何将它与我已经拥有的东西结合起来。我听说过 cv2 库,但我一直无法让它工作。
我的代码如下:
training_set = pd.DataFrame({'Images': training_imgs,'Labels': training_labels})
train_dataGen = ImageDataGenerator(rescale=1./255)
train_generator = train_dataGen .flow_from_dataframe(
dataframe = training_set, directory="",
x_col="Images", y_col="Labels",
class_mode="categorical",
target_size=(224,224), batch_size=32)
## Steps to plot the images
imgs, labels = next(train_generator)
for i in range(batch_size):
image = imgs[i]
plt.imshow(image)
plt.show()
解决方案
你快完成了。如果您使用 keras,则此处不需要 opencv。
image = imgs[i,:,:,:] # batch_size, height, width, channels
print(np.shape(image) # should be (224,224) in case your image is grayscale
plt.imshow(image)
plt.show()
这将显示您调整大小的图像并打印它的形状。如果要更改调整大小方法的插值方法,可以查看文档。默认情况下它是双线性的,我认为这就是您要寻找的。
编辑 0:如果您想为图像上的任何类型的预处理(调整大小等)创建自定义函数,您可以preprocessing_function
在您的ImageDataGenerator
方法中定义。此功能适用于批次中的每个图像。
import cv2
def preprocess(image):
# feel free to define your own function here
# be sure this function returns an image
processed_image = cv2.resize(image, dsize=(224,224))
return processed_image
train_dataGen = ImageDataGenerator(preprocessing_function=preprocess,
rescale=1./255)
推荐阅读
- kubernetes - Kubernetes:如何确保在每个工作节点上安排一个 pod?
- c# - 如何将我从 DI 容器获取的参数从默认的空构造函数传递到基类?
- machine-learning - Kaggle - 猫与狗(用户警告:在 x_col="filename" 中发现 20000 个无效图像文件名。这些文件名将被忽略。)
- javascript - 删除子元素时未触发鼠标悬停
- python - 我如何弄清楚失败的原因?(crontab 或路径)
- pandas - 合并两个具有重叠 MultiIndex 列的 DataFrame
- javascript - 在每次路由更改时重新渲染特定组件
- vb.net - VB .NET BC30002 VB.NET 类型未定义
- react-native - 反应本机博览会错误。我应该怎么办?
- python - Python win32api 无法在 Windows Paint 应用程序上绘图