使用 python 从图像中删除白色 space
Remove white space from an image using python
我需要删除多张包含空白的图像。只需裁剪图像即可去除空白
这是我到目前为止尝试过的代码(这是搜索的结果)
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)
这是示例图片
这是期望的输出
代码近乎完美。由于滚动条,它无法在右侧裁剪。而且它不考虑一些填充(根据评论你喜欢)。
我去掉的是拓扑修改
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)
我需要删除多张包含空白的图像。只需裁剪图像即可去除空白 这是我到目前为止尝试过的代码(这是搜索的结果)
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)
这是示例图片
这是期望的输出
代码近乎完美。由于滚动条,它无法在右侧裁剪。而且它不考虑一些填充(根据评论你喜欢)。
我去掉的是拓扑修改
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)