numpy 利用opencv检测掩模图像中的锐角线

baubqpgj  于 2024-01-08  发布在  其他
关注(0)|答案(1)|浏览(133)

我目前正在做一个项目,我需要识别和提取锐角线的区域,类似于“V”形,从给定的掩模图像。
x1c 0d1x的数据



所需输出如下

我尝试使用以下Python代码来生成掩码图像:

  1. img = cv2.imread(img_f)
  2. hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
  3. #range for red color
  4. lower_r = np.array([0,238,132])
  5. upper_r = np.array([25,255,255])
  6. mask = cv2.inRange(hsv,lower_r,upper_r)
  7. kernel = np.ones((5, 5), np.uint8)
  8. mask = cv2.dilate(mask, kernel, iterations=3)
  9. plt.imshow(mask,cmap='gray')
  10. plt.show()

字符串
然而,我在检测掩模图像中的特定锐角线方面面临挑战。我相信在我的方法中可能需要修改或额外的技术。
有没有人可以提供指导或建议修改我的代码,这将有助于准确地识别和提取类似于“V”形的锐角线的所需区域?
任何见解,代码片段,或推荐的库为这项任务将不胜感激。提前感谢您的帮助!
[基于答案]我根据给出的答案尝试了以下方法

  1. import cv2
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. # Read the image
  5. img_f = 'path/to/your/image.jpg'
  6. img = cv2.imread(img_f)
  7. # Convert the image to HSV
  8. hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
  9. # Define the range for red color in HSV
  10. lower_r = np.array([0, 238, 132])
  11. upper_r = np.array([25, 255, 255])
  12. # Create a mask for red color
  13. mask = cv2.inRange(hsv, lower_r, upper_r)
  14. # Dilate the mask to make sure it covers the entire object
  15. kernel = np.ones((5, 5), np.uint8)
  16. mask = cv2.dilate(mask, kernel, iterations=3)
  17. # Find lines using Hough Transform
  18. lines = cv2.HoughLines(mask, 1, np.pi / 180, 100)
  19. # Draw lines on the original image if the angle is less than 90 degrees
  20. if lines is not None:
  21. for line in lines:
  22. for rho, theta in line:
  23. a = np.cos(theta)
  24. b = np.sin(theta)
  25. x0 = a * rho
  26. y0 = b * rho
  27. x1 = int(x0 + 1000 * (-b))
  28. y1 = int(y0 + 1000 * (a))
  29. x2 = int(x0 - 1000 * (-b))
  30. y2 = int(y0 - 1000 * (a))
  31. # Check if the points are within the image boundaries
  32. if 0 <= y1 < mask.shape[0] and 0 <= x1 < mask.shape[1] and \
  33. 0 <= y2 < mask.shape[0] and 0 <= x2 < mask.shape[1]:
  34. # Check if the intersection point is in the foreground (non-zero in the mask)
  35. if mask[y1, x1] > 0 and mask[y2, x2] > 0:
  36. # Calculate the angle between the lines
  37. angle = np.degrees(np.arctan2(y2 - y1, x2 - x1))
  38. # Draw lines in red if the angle is less than 90 degrees
  39. if abs(angle) < 90:
  40. cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
  41. # Display the result
  42. plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  43. plt.show()


按照上面的方法,我找不到任何一对线的交点位于前景,对此方法的任何修改或建议都将受到欢迎。

eimct9ow

eimct9ow1#

我自己没有尝试过,但你可以做以下事情:
1.应用Hough变换检测直线
1.检测每对直线的交点
1.如果一个交点是前景点之一,然后看看两条线之间的Angular ,如果它小于90度,那么它是一个锐角
或者,您可以执行以下操作:对于每个前景点,查看它满足多少个线方程,如果数量为2,则它位于两条线的交点处。

相关问题