寻找图片中心图像的边界

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值