简体   繁体   English

使用 python 从图像中删除空白

[英]Remove white space from an image using python

There are multiple images that have white spaces that I need to remove.有多个图像有我需要删除的空白。 Simply crop the image so as to get rid of the white spaces Here's the code I tried so far (this is a result of search)只需裁剪图像以消除空格这是我到目前为止尝试的代码(这是搜索的结果)

 import numpy as np import cv2 img = cv2.imread('Sample.png') img = img[:-5,:-5] gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = 255*(gray < 128).astype(np.uint8) gray = cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((2, 2), dtype=np.uint8)) coords = cv2.findNonZero(gray) x, y, w, h = cv2.boundingRect(coords) rect = img[y:y+h, x:x+w] cv2.imshow("Cropped", rect) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite("Output.png", rect)

Here's the sample image这是示例图像

在此处输入图像描述

And this is the desired output这是所需的 output

在此处输入图像描述

The code is almost perfect.代码几乎是完美的。 It just can't crop on the right side because of the scrollbar.由于滚动条,它无法在右侧裁剪。 And it does not consider some padding (which you liked according the comments).而且它不考虑一些填充(根据评论你喜欢)。

The thing I removed is the topology modification.我删除的是拓扑修改。

 import numpy as np import cv2 img = cv2.imread('cropwhitefromimage.png') scrollbarright = 20 img = img[:,:-scrollbarright] gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = 255*(gray < 128).astype(np.uint8) coords = cv2.findNonZero(gray) x, y, w, h = cv2.boundingRect(coords) padding = 10 rect = img[y-padding:y+h+padding, x-padding:x+w+padding] cv2.imshow("Cropped", rect) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite("cropwhitefromimage_result.png", rect)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM