Approach:
- 迭代遮罩中的每个轮廓
- 查找遮罩中存在的像素的位置
- 在给定图像中找到相应的值
- 计算并绘制直方图
Code:
# reading given image in grayscale
img = cv2.imread('apples.jpg', 0)
# reading the mask in grayscale
img_mask = cv2.imread(r'apples_mask.jpg', 0)
# binarizing the mask
mask = cv2.threshold(img_mask,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
# find contours on the mask
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# the approach is encoded within this loop
for i, c in enumerate(contours):
# create a blank image of same shape
black = np.full(shape = im.shape, fill_value = 0, dtype = np.uint8)
# draw a single contour as a mask
single_object_mask = cv2.drawContours(black,[c],0,255, -1)
# coordinates containing white pixels of mask
coords = np.where(single_object_mask == 255)
# pixel intensities present within the image at these locations
pixels = img[coords]
# plot histogram
plt.hist(pixels,256,[0,256])
plt.savefig('apples_histogram_{}.jpg'.format(i)')
# to avoid plotting in the same plot
plt.clf()
Result: (the following are the 3 histogram plots)
如果删除plt.clf()
,所有直方图将绘制在一个绘图上
您可以为您的用例扩展相同的方法
原始图像: