cv2 裁剪图片、删除过多冗余的背景

代码:

import numpy as np
import cv2
import matplotlib.pyplot as plt


def crop_image_from_gray(img, boundary=7):
    # 转为灰度图
    # 注意, cv2.imread读取的是bgr格式, 而不是rgb
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    mask = gray_img > boundary
    img1 = img[:, :, 0][np.ix_(mask.any(1), mask.any(0))]
    img2 = img[:, :, 1][np.ix_(mask.any(1), mask.any(0))]
    img3 = img[:, :, 2][np.ix_(mask.any(1), mask.any(0))]
    img = cv2.merge((img1, img2, img3))
    return img


img = cv2.imread('1.png')
img = crop_image_from_gray(img, 7)
cv2.imwrite('2.png', img)

img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.figure()
plt.imshow(img_rgb)
plt.show()

效果展示:

原图:
cv2 裁剪图片、删除过多冗余的背景_第1张图片

处理后:

你可能感兴趣的:(图像处理与分析,计算机视觉,opencv,python)