【发布时间】:2017-06-27 00:02:42
【问题描述】:
我有一个二值图像,我需要找到黑色区域的 x 和 y 的平均值。这些值是针对一组二值图像计算的,并且绘制了它们的 x 和 y 的平均值我不知道如何找到这个区域并计算它们的 x 和 y 的平均值。任何帮助都将不胜感激。
【问题讨论】:
-
使用
cv2.moments
标签: python-2.7 opencv image-processing video-processing
我有一个二值图像,我需要找到黑色区域的 x 和 y 的平均值。这些值是针对一组二值图像计算的,并且绘制了它们的 x 和 y 的平均值我不知道如何找到这个区域并计算它们的 x 和 y 的平均值。任何帮助都将不胜感激。
【问题讨论】:
cv2.moments
标签: python-2.7 opencv image-processing video-processing
如果黑色像素没有注册在某些数据结构中,只需计算黑色像素的质心:
sx = 0
sy = 0
black_cnt = 0
for y in y-range
for x in x-range
if black(x,y)
sx = sx + x
sy = sy + y
black_cnt++
sx = sx / black_cnt
sy = sy / black_cnt
【讨论】:
IndexError: index 255 is out of bounds for axis 0 with size 200这个错误
im = cv2.imread('v6.tif', 0) ret, thresh = cv2.threshold(im, 120, 255, 1) a = len(im) print thresh b = a+2 sx = 0 sy = 0 blackc = 0 for x in range(a): for y in range(a): pixel = im[x,y] if pixel == 0: sx = sx+x sy = sy+y blackc +=1 print blackc cv2.waitKey()我在做这个
for x in range(a),而 x 应该在范围(宽度)内,而 y 在范围(高度)内
您可以使用轮廓矩获得平均位置。
为了找到均值,您必须计算轮廓的一阶矩。
代码:
#---Read image and obtain threshold---
im = cv2.imread('1.jpg', 1)
img = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img, 120, 255, 1)
#---Obtain contours---
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = contours
cv2.drawContours(im, contours, -1, (0, 255, 0), 1)
#---Compute the center/mean of the contours---
for c in cnts:
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
print cX
print cY
值cX 和cY 具有轮廓的平均位置。
【讨论】:
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) ValueError: too many values to unpack这个错误
_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)