我是Open CV和计算机视觉的新手,所以我谦虚地问一个问题。使用pi摄像头我录制视频,实时我可以识别其他颜色的蓝色(我看到蓝色为白色,其他颜色为黑色)。
我想测量区域底部的长度(因为我有一个白色矩形和一个黑色矩形)。这两个矩形一起创建了方框。
代码摘录:
<div class="topnav">
<ul>
<li><a class="active" href="index.html">Home</a></li>
<li class="dropdown"><a href="javascript:void(0)" class="dropbtn">Products</a>
<div class="dropdown-content">
<a href="#">Computers</a>
<a href="#">Tablets</a>
<a href="#">Cell Phones</a>
<a href="#">Wearable Technologies</a>
<a href="#">Accessories</a>
</div>
</li>
<li class="dropdown"><a href="javascript:void(0)" class="dropbtn">Brands</a>
<div class="dropdown-content">
<a href="#">Apple</a>
<a href="#">Samsung</a>
<a href="#">Lenovo</a>
<a href="#">Dell</a>
<a href="#">HP</a>
<a href="#">Sony</a>
<a href="#">Panasonic</a>
<a href="#">Motorola</a>
<a href="#">HTC</a>
</div>
</li>
<li><a href="deals.html">Deals</a></li>
</ul>
</div>
答案 0 :(得分:0)
假设输入帧将具有&#34;接近矩形&#34;形状(以下代码效果最佳),您必须使用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))