英文:
Extracting a red color and its area from an image using CV2
问题
I have an image from a simulation I performed (the image is attached). I want to contour the red coulour in the center of plate and calculate its area considering that the plate is with dimensions of 1X1 cm.
I have tried doing it myself using Python and OpenCV but have failed. Can anyone help please?
英文:
I have an image from a simulation I performed (the image is attached). I want to contour the red coulour in the center of plate and calculate its area considering that the plate is with dimensions of 1X1 cm.
I have tried doing it myself using Python and OpenCV but have failed. Can anyone help please?
答案1
得分: 2
首先,你会想要一个 "遮罩"。
然后,你可以计算遮罩中的元素数。
image = ...
(height, width) = image.shape[:2]
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
# 色调,饱和度,亮度
# 红色区域饱和度高且很明亮
# 红色接近0度色调
# 因为我们处于一个圆上,这些值可能跨足 340 到 20 度
# 色调映射到 0..180(uint8)对应 0..360 度
# 我们需要两个范围,因为我们从两侧横跨 0,并且 inRange() 不能一次处理这两个范围
mask1 = cv.inRange(hsv, (170, 128, 128), (180, 255, 255)) # 粉红色偏红
mask2 = cv.inRange(hsv, ( 0, 128, 128), ( 10, 255, 255)) # 偏黄的红
mask = mask1 | mask2
红色计数 = cv.countNonZero(mask)
分数 = 红色计数 / (宽度 * 高度)
print(f"{分数:.2%}")
# 0.76%
是的,正确。0.76%。不是很大的区域。
这是在你照片的裁剪上计算出的遮罩:
英文:
First you'll want a "mask".
Then you can count the number of elements in the mask.
image = ...
(height, width) = image.shape[:2]
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
# hue, saturation, value
# the red area is well saturated and very bright
# red is near 0 degrees of hue
# since we're on a circle, those values might span 340 to 20 degrees
# hues are mapped into 0..180 (uint8) for 0..360 degrees
# we need two ranges because we're spanning across 0 from both sides and inRange() can't handle that at once
mask1 = cv.inRange(hsv, (170, 128, 128), (180, 255, 255)) # pinkish red
mask2 = cv.inRange(hsv, ( 0, 128, 128), ( 10, 255, 255)) # yellowish red
mask = mask1 | mask2
red_count = cv.countNonZero(mask)
fraction = red_count / (width * height)
print(f"{fraction:.2%}")
# 0.76%
Yes, that's correct. 0.76%. It's not much area.
This is the mask calculated on a crop of your picture:
答案2
得分: 0
- 查找红色的上限和下限范围。
- 使用 cv2.inRange() 获取黑白掩模。使用 inRange 函数的链接。
- 现在你有了一个掩模,使用 cv2.findContours 获取所需的轮廓,然后在迭代过程中使用 cv2.contourArea() 获取面积。
英文:
- Find the upper range and lower range of the colour red.
- Use cv2.inRange() to get a black and white mask. The link to use inRange function
- Now that you have a mask, use cv2.findContours to get the required contours and while iterating, get the area by using cv2.contourArea()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论