python - numpy图像,裁剪一侧,用黑色填充另一侧

标签 python image numpy crop

我有一个分辨率为 816x624 的图像,需要用它制作一个 640x640 的图像。

为此,我必须裁剪长边(居中),并用黑色填充短边(居中)。生成的图像应位于起始图像的中心,顶部和底部有一个小黑条。

如何做到这一点?

我尝试过:

 crop_img = img1[int(h1 / 2 - 640 / 2):int(h1 / 2 + 640 / 2),
                           int(w1 / 2 - 640 / 2):int(w1 / 2 + 640/ 2)]

但这不起作用,因为 h1 小于 640。

enter image description here

最佳答案

给定输入图像 img、预期高度 h 和预期宽度 w:

def resize_img(img, h, w):

  #cut the image
  cutted_img =  img[
      max(0, int(img.shape[0]/2-h/2)):min(img.shape[0], int(img.shape[0]/2+h/2)),
      max(0, int(img.shape[1]/2-w/2)):min(img.shape[1], int(img.shape[1]/2+w/2)),
  ]

  #pad the image
  padded_img = np.zeros(shape=(h,w,3), dtype=img.dtype)
  padded_img[
      int(padded_img.shape[0]/2-cutted_img.shape[0]/2):int(padded_img.shape[0]/2+cutted_img.shape[0]/2),
      int(padded_img.shape[1]/2-cutted_img.shape[1]/2):int(padded_img.shape[1]/2+cutted_img.shape[1]/2),
  ] = cutted_img

  return padded_img

一些例子:

url = "https://www.planetware.com/wpimages/2020/02/france-in-pictures-beautiful-places-to-photograph-eiffel-tower.jpg"
response = requests.get(url)
start_img = np.array(PIL.Image.open(BytesIO(response.content)))
plt.imshow(start_img)
plt.show() #shape = (487, 730, 3)

plt.imshow(resize_img(start_img, 640, 640))
plt.show() #shape = (640, 640, 3)

我在其他一些图片上进行了测试:

形状 = (1020, 680, 3)

形状 = (450, 254, 3)

形状 = (847, 564, 3)

所有调整大小的图像的尺寸均为(640, 640, 3),并且似乎已正确填充。

PS。我使用了以下库:

import numpy as np
from matplotlib import pyplot as plt
import PIL
import requests
from io import BytesIO

关于python - numpy图像,裁剪一侧,用黑色填充另一侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74344904/

相关文章:

python - 导入错误 : No module named netifaces

jquery - 这个切换功能有什么问题吗?

html - 想要更改当前页面的标签图像

java - 如何使用 Apache POI 锁定 docx 中图像的长宽比?

python - Scipy:链接标签到输出 Z

python - 基于端点的旋转

python - 在 Python 中显示具有较少关键点的 Brisk 关键点

python 无我

python - Python List List 切片列表

python - np.array with inhomogeneos data (str+float)