代码:
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()
效果展示:
处理后: