opencv 使用CV2从图像中提取红色及其区域

8dtrkrch  于 2023-05-23  发布在  其他
关注(0)|答案(2)|浏览(468)

我有一个图像从模拟我执行(图像是附加的)。我想在平板中心绘制红色轮廓,并考虑平板尺寸为1X1 cm,计算其面积。

我曾经尝试过使用Python和OpenCV,但都失败了。有人能帮忙吗?

13z8s7eq

13z8s7eq1#

首先你要一个“面具”
然后你可以计算掩码中元素的数量。

  1. image = ...
  2. (height, width) = image.shape[:2]
  3. hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
  4. # hue, saturation, value
  5. # the red area is well saturated and very bright
  6. # red is near 0 degrees of hue
  7. # since we're on a circle, those values might span 340 to 20 degrees
  8. # hues are mapped into 0..180 (uint8) for 0..360 degrees
  9. # we need two ranges because we're spanning across 0 from both sides and inRange() can't handle that at once
  10. mask1 = cv.inRange(hsv, (170, 128, 128), (180, 255, 255)) # pinkish red
  11. mask2 = cv.inRange(hsv, ( 0, 128, 128), ( 10, 255, 255)) # yellowish red
  12. mask = mask1 | mask2
  13. red_count = cv.countNonZero(mask)
  14. fraction = red_count / (width * height)
  15. print(f"{fraction:.2%}")
  16. # 0.76%

是的,没错。0.76%,面积不大。
这是根据图片裁剪计算的蒙版:

展开查看全部
xwmevbvl

xwmevbvl2#

1.找出红色的上限和下限。
1.使用cv2.inRange()获取白色蒙版。The link to use inRange function
1.现在您已经有了一个遮罩,使用cv2.findContours来获取所需的轮廓,并在迭代时使用cv2.contourArea()获取面积

相关问题