裁剪中心部分的numpy图像 [英] crop center portion of a numpy image

查看:2309
本文介绍了裁剪中心部分的numpy图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个宽x和高y的numpy图像。
我必须将图像的中心部分裁剪为宽度cropx和height cropy。让我们假设cropx和cropy是正非零整数并且小于相应的图像大小。对输出图像应用切片的最佳方法是什么?

Let's say I have a numpy image of some width x and height y. I have to crop the center portion of the image to width cropx and height cropy. Let's assume that cropx and cropy are positive non zero integers and less than the respective image size. What's the best way to apply the slicing for the output image?

推荐答案

这些方面的东西 -

Something along these lines -

def crop_center(img,cropx,cropy):
    y,x = img.shape
    startx = x//2-(cropx//2)
    starty = y//2-(cropy//2)    
    return img[starty:starty+cropy,startx:startx+cropx]

样品运行 -

In [45]: img
Out[45]: 
array([[88, 93, 42, 25, 36, 14, 59, 46, 77, 13, 52, 58],
       [43, 47, 40, 48, 23, 74, 12, 33, 58, 93, 87, 87],
       [54, 75, 79, 21, 15, 44, 51, 68, 28, 94, 78, 48],
       [57, 46, 14, 98, 43, 76, 86, 56, 86, 88, 96, 49],
       [52, 83, 13, 18, 40, 33, 11, 87, 38, 74, 23, 88],
       [81, 28, 86, 89, 16, 28, 66, 67, 80, 23, 95, 98],
       [46, 30, 18, 31, 73, 15, 90, 77, 71, 57, 61, 78],
       [33, 58, 20, 11, 80, 25, 96, 80, 27, 40, 66, 92],
       [13, 59, 77, 53, 91, 16, 47, 79, 33, 78, 25, 66],
       [22, 80, 40, 24, 17, 85, 20, 70, 81, 68, 50, 80]])

In [46]: crop_center(img,4,6)
Out[46]: 
array([[15, 44, 51, 68],
       [43, 76, 86, 56],
       [40, 33, 11, 87],
       [16, 28, 66, 67],
       [73, 15, 90, 77],
       [80, 25, 96, 80]])

这篇关于裁剪中心部分的numpy图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆