删除图像的空白python opencv

pprl5pva  于 2022-11-15  发布在  Python
关注(0)|答案(1)|浏览(199)

我想从一个图像中选择一个矩形框,所有的内容都放在那里。换句话说,我想删除图像的背景中不重要的像素(与内容无关的像素)。然而,输出的图像应该是一个矩形。
在Python OpenCV中最简单的方法是什么?(我将从一个文件夹导入文件......如果我可以自动化这个过程就更好了)

zsohkypk

zsohkypk1#

我希望你问的是“自动裁剪掉图像的白色”。这里我们假设一个二进制图像:像素具有高值和低值。

def focusToContent(img):
    img_ = 255*(img < 128).astype(np.uint8) 
    coords = cv.findNonZero(img_) # Find all non-zero points (text)
    x, y, w, h = cv.boundingRect(coords) # Find minimum spanning bounding box
    
    rect = img[y:y+h, x:x+w] # Crop the image - note we do this on the original image
    rect_originalSized = cv.resize(rect,(img.shape))
    return rect_originalSized

img应为opencv图像(具有正确数据类型的numpy数组)
测试代码

#testing
img = cv.imread(r"D:/ENTC/SEM_4/EN2550 - Fundamentals of Image Processing and Machine Vision/~images/int-rec/test/1650009171.5083215.png",0)
assert img is not None
focused = focusToContent(img)

fig,ax = plt.subplots(1,2)
ax[0].imshow(img,cmap="gray")
ax[1].imshow(focused,cmap="gray")
plt.show()

相关问题