假设这张图片(1.jpg)与脚本在同一个文件夹中。
还有下面这张遮罩图片:
我写了一个非常粗略的解决方案。
import numpy as np
import sys
import cv2
image = cv2.imread('1.jpg')
mask = np.zeros(image.shape, dtype=np.uint8)
roi_corners = np.array([[(10,10), (200,200), (10,200)]], dtype=np.int32)
white = (255, 255, 255)
cv2.fillPoly(mask, roi_corners, white)
masked_image = cv2.bitwise_and(image, mask)
iii = 0
while not np.sum(masked_image[iii,:,:]):
resized_top = masked_image[iii+1:,:,:]
iii = iii + 1
size_img = resized_top.shape
iii = size_img[0]
while not np.sum(resized_top[iii-2:iii-1,:,:]):
resized_bottom = resized_top[0:iii-1,:,:]
iii = iii - 1
iii = 0
while not np.sum(resized_bottom[:,iii,:]):
resized_left = resized_bottom[:,iii+1:,:]
iii = iii + 1
size_img = resized_left.shape
iii = size_img[1]
print iii
while not np.sum(resized_left[:,iii-2:iii-1,:]):
resized_right = resized_left[:,0:iii-1:,:]
iii = iii - 1
cv2.imshow('masked image', resized_right)
cv2.waitKey()
cv2.destroyAllWindows()
结果: