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
# print('图片大小为' + str(im_shape))
images_background = im[2, 2] # 图像左上角像素点值一定是该图像的背景值
# print('当前图片背景值为' + str(images_background))
end_flag = 0
# 找到图形上边界
for row in range(0, im_shape[0]):
if end_flag == 1:
# print('找到上边界行:' + str(shape[0]))
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:
# print('找到下边界行:' + str(shape[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:
# print('找到左边界列:' + str(shape[2]))
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:
# print('找到右边界列:' + str(shape[3]))
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]] # y1:y2,x1:x2
cv2.imwrite('./225.png', im)
寻找图片中心图像的边界
最新推荐文章于 2024-05-30 11:43:13 发布