繁体   English   中英

使用Python测量OpenCv上像素之间的距离

[英]Measuring the distance between pixels on OpenCv with Python

我是Open CV和计算机视觉的新手,所以我谦虚地问一个问题。 使用pi摄像机可以录制视频,并且可以实时识别其他颜色的蓝色(我看到蓝色为白色,而其他颜色为黑色)。

在此处输入图片说明

我想测量区域底部的长度(因为我有一个白色矩形和一个黑色矩形)。 这两个矩形共同创建了方形框架。

在此处输入图片说明

代码摘录:

# Take each frame
_, frame = cap.read(0)

# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

# define range of blue color in HSV
lower_blue = np.array([80,30,30])
upper_blue = np.array([130,150,210])

# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)    
# applica filtri morfologici
mask = cv2.erode(mask, spotFilter)
mask = cv2.dilate(mask, maskMorph)
# ^Now the mask is a black and white image.
# ^Get height of the black region in this image

# Bitwise-AND mask and original image
res = cv2.bitwise_and(frame,frame, mask= mask)
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)

假设输入帧将具有“接近矩形”的形状(以下代码最有效),则必须使用findContours函数获取黑色区域的边界,并使用boundingRect函数获取其尺寸。

mask = cv2.imread('mask.png') #The mask variable in your code
# plt.imshow(mask)
thresh_min,thresh_max = 127,255
ret,thresh = cv2.threshold(mask,thresh_min,thresh_max,0)
# findContours requires a monochrome image.
thresh_bw = cv2.cvtColor(thresh, cv2.COLOR_BGR2GRAY)
# findContours will find contours on bright areas (i.e. white areas), hence we'll need to invert the image first
thresh_bw_inv = cv2.bitwise_not(thresh_bw)

_, contours, hierarchy = cv2.findContours(thresh_bw_inv,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# ^Gets all white contours

# Find the index of the largest contour
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt=contours[max_index]

x,y,w,h = cv2.boundingRect(cnt)
#Draw the rectangle on original image here.
cv2.rectangle(mask,(x,y),(x+w,y+h),(0,255,0),2)
plt.imshow(mask)
print("Distances: vertical: %d, horizontal: %d" % (h,w))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM