mask : 提取感兴趣区域
具体代码:
import cv2
import matplotlib.pyplot as plt
import numpy as np
def show_image(image, title, pos):
img_RGB = image[:, :, ::-1]
plt.title(title)
plt.subplot(2, 2,pos)
plt.imshow(img_RGB)
def show_histogram(hist, title, pos, color):
plt.subplot(2, 2, pos)
plt.title(title)
plt.xlim([0, 256])
plt.plot(hist, color=color)
def main():
plt.figure(figsize=(12, 7))
plt.suptitle("Gray Image and Histogram with mask", fontsize=4, fontweight="bold")
img_gray = cv2.imread("3.jpg", cv2.COLOR_BGR2GRAY)
img_gray_hist = cv2.calcHist([img_gray], [0], None, [256], [0, 256])
show_image(img_gray, "image gray", 1)
show_histogram(img_gray_hist, "image gray histogram", 2, "m")
mask = np.zeros(img_gray.shape[:2], np.uint8)
mask[130:500, 200:400] = 255
img_mask_hist = cv2.calcHist([img_gray], [0], mask, [256], [0, 256])
mask_img = cv2.bitwise_and(img_gray, img_gray, mask = mask)
show_image(mask_img, "gray image with mask", 3)
show_histogram(img_mask_hist, "histogram with masked gray image", 4,"m")
plt.show()
if __name__ == '__main__':
main()
运行截图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/06329f0d0f26bbbaeed68ad79669dcfb.png)