裁剪图像背景区域

import os
import cv2
path1 = "./file1_path/"
path2 = "./file2_path/"
files = os.listdir(path1)
for file in files:
    if "DS_Store" in file:
        continue
    img = cv2.imread(path1+file, 0)
    img1 = cv2.imread(path1+file)
    rows, cols = img.shape[0], img.shape[1]
    voxel_l, voxel_r, voxel_t, voxel_b = cols, 0, rows, 0
    for row in range(img.shape[0]):
        for col in range(img.shape[1]):
            if img[row][col] > 0:
                if col < voxel_l:
                    voxel_l = col
                if col > voxel_r:
                    voxel_r = col
                if row < voxel_t:
                    voxel_t = row
                if row > voxel_b:
                    voxel_b = row
    crop = img1[voxel_t:voxel_b, voxel_l:voxel_r, :]
    cv2.imwrite(path2+file, crop)
发布了315 篇原创文章 · 获赞 119 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/w144215160044/article/details/104915593