我正在尝试计算沿图像质心垂直和水平分割的两半图像的像素比。目的是查看图像的对称/不对称程度。下面是代码、原始图像和显示我正在尝试做的事情的图像。
到目前为止,我已经对图像进行了阈值处理,围绕其周边创建了一个轮廓,填充了该轮廓,并计算并标记了质心。
我一直在研究如何 (a) 将轮廓一分为二,以及 (b) 计算轮廓图像两半之间的像素比(仅黑色部分)。感谢您的任何建议和/或帮助。
# import packages
import argparse
import imutils
import cv2
# construct argument parser
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to the input image")
args = vars(ap.parse_args())
# load the image
image = cv2.imread(args["image"])
# convert it to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# threshold the image
(T, threshInv) = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
# find outer contour of thresholded image
cnts = cv2.findContours(threshInv.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
# loop over the contour/s for image moments
for c in cnts:
# compute the center of the contour
M = cv2.moments(c)
# calculate the centroid
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
# draw and fill the contour on the image
cv2.drawContours(image, [c], -1, (0, 0, 0), thickness=cv2.FILLED)
# draw the centroid on the filled contour
cv2.circle(image, (cX, cY), 7, (255, 0, 0), -1)
# show the image
cv2.imshow("Image", image)
cv2.waitKey(0)
原图:
目标:
最佳答案
第 1 部分:
图片可以分别裁剪如下图
top_half = image[0:cY, :]
bottom_half = image[cY:, :]
left_half = image[:, 0:cX]
right_half = image[:, cX:]
第 2 部分:
为了计算比率,我们只取上述 4 个裁剪图像中的任何一个 channel 。该 channel 将是一个二值图像,仅由白色 (255) 像素和黑色 (0) 像素组成。我们将计算每一半中黑色像素的数量并划分:
top_half = top_half[:,:,1]
bottom_half = bottom_half[:,:,1]
left_half = left_half[:,:,1]
right_half = right_half[:,:,1]
以上均为单 channel 图像
top_bottom_ratio = int(np.size(top_half) - np.count_nonzero(top_half)/np.size(bottom_half) - np.count_nonzero(bottom_half)
np.size()
给出图像中的像素总数
np.count_nonzero()
给出白色像素的数量
你可以做同样的事情来找到左右两半之间的比例
关于python - 计算图像两半的像素比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72623020/