import cv2
from PIL import Image
import os
import os.path
def find_crop_position(path: str = ''):
shape = [0, 0, 0, 0]
im = cv2.imread(path, 0)
im = cv2.medianBlur(im, 5)
ret, im = cv2.threshold(im, 30, 255, cv2.THRESH_BINARY)
im_shape = im.shape
images_background = im[2, 2]
end_flag = 0
for row in range(0, im_shape[0]):
if end_flag == 1:
end_flag = 0
break
for col in range(0, im_shape[1]):
if im[row, col] != images_background and end_flag == 0:
shape[0] = row
end_flag = 1
for row in range(im_shape[0] - 1, -1, -1):
if end_flag == 1:
end_flag = 0
break
for col in range(0, im_shape[1]):
if im[row, col] != images_background and end_flag == 0:
shape[1] = row
end_flag = 1
for col in range(0, im_shape[1]):
if end_flag == 1:
end_flag = 0
break
for row in range(0, im_shape[0]):
if im[row, col] != images_background and end_flag == 0:
shape[2] = col
end_flag = 1
for col in range(im_shape[1] - 1, -1, -1):
if end_flag == 1:
end_flag = 0
break
for row in range(0, im_shape[0]):
if im[row, col] != images_background and end_flag == 0:
shape[3] = col
end_flag = 1
return shape
if __name__ == '__main__':
image_path = 'D:/program/tool/protest/train/image/225.jpg'
cut_shape = find_crop_position(path=image_path)
im = cv2.imread(image_path)
im = im[cut_shape[0]:cut_shape[1], cut_shape[2]:cut_shape[3]]
cv2.imwrite('./225.png', im)