如何在python numpy中从周围的白色背景裁剪对象? [英] How can I crop an object from surrounding white background in python numpy?

查看:81
本文介绍了如何在python numpy中从周围的白色背景裁剪对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的图像数据集.

I have dataset of images which are all like this one.

任务是尽可能裁剪图像周围的空白并返回包含较少白色周围图像的图像:

The task is to crop the white space surrounding the image as much as possible and return the image that contains less white surrounding image:

def crop_object(img):
    lst = []
    # hold min and max of height
    for i in range(img.shape[0]):
        r = img[:,i,0]
        g = img[:,i,1]
        b = img[:,i,2]

        if (np.min(r) != 255) or (np.min(g) != 255) or (np.min(b) != 255):
            lst.append(i)
    a1 = min(lst)
    a2 = max(lst)

    for i in range(img.shape[1]):
        r = img[i,:,0]
        g = img[i,:,1]
        b = img[i,:,2]

        if (np.min(r) != 255) or (np.min(g) != 255) or (np.min(b) != 255):
            lst.append(i)
    a3 = min(lst)
    a4 = max(lst)

    return img [a3:a4, a1:a2, :]

我想要一种更Python化的方式来处理此问题.诸如更少的代码和更快的运行之类的东西.

I want a more pythonic way to handle this. Something like less code and faster run.

你能帮我吗?

推荐答案

使用NumPy裁剪图像的黑色边框的启发 ,这是两种裁剪方式-

Inspired by Crop black border of image using NumPy, here are two ways of cropping -

# I. Crop to remove all black rows and columns across entire image
def crop_image(img):
    mask = img!=255
    mask = mask.any(2)
    mask0,mask1 = mask.any(0),mask.any(1)
    return img[np.ix_(mask1,mask0)]

# II. Crop while keeping the inner all black rows or columns
def crop_image_v2(img):
    mask = img!=255
    mask = mask.any(2)
    mask0,mask1 = mask.any(0),mask.any(1)
    colstart, colend = mask0.argmax(), len(mask0)-mask0[::-1].argmax()+1
    rowstart, rowend = mask1.argmax(), len(mask1)-mask1[::-1].argmax()+1
    return img[rowstart:rowend, colstart:colend]

使用公差

如该链接文章中所述,我们可能要使用一些容忍度.相同地,遮罩创建步骤将修改为-

As mentioned in that linked post, we might want to use some tolerance. For the same, the mask creation step would modify to -

tol = 255 # tolerance value
mask = img<tol

时间-

# Read in given image
In [119]: img = cv2.imread('9Aplg.jpg')

# With original soln
In [120]: %timeit crop_object(img)
5.46 ms ± 401 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [121]: %timeit crop_image(img)
923 µs ± 4.96 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [122]: %timeit crop_image_v2(img)
672 µs ± 53.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

这篇关于如何在python numpy中从周围的白色背景裁剪对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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