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

baubqpgj  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(97)

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



所需输出如下

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

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

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

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Read the image
img_f = 'path/to/your/image.jpg'
img = cv2.imread(img_f)

# Convert the image to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Define the range for red color in HSV
lower_r = np.array([0, 238, 132])
upper_r = np.array([25, 255, 255])

# Create a mask for red color
mask = cv2.inRange(hsv, lower_r, upper_r)

# Dilate the mask to make sure it covers the entire object
kernel = np.ones((5, 5), np.uint8)
mask = cv2.dilate(mask, kernel, iterations=3)

# Find lines using Hough Transform
lines = cv2.HoughLines(mask, 1, np.pi / 180, 100)

# Draw lines on the original image if the angle is less than 90 degrees
if lines is not None:
    for line in lines:
        for rho, theta in line:
            a = np.cos(theta)
            b = np.sin(theta)
            x0 = a * rho
            y0 = b * rho
            x1 = int(x0 + 1000 * (-b))
            y1 = int(y0 + 1000 * (a))
            x2 = int(x0 - 1000 * (-b))
            y2 = int(y0 - 1000 * (a))

            # Check if the points are within the image boundaries
            if 0 <= y1 < mask.shape[0] and 0 <= x1 < mask.shape[1] and \
               0 <= y2 < mask.shape[0] and 0 <= x2 < mask.shape[1]:
                
                # Check if the intersection point is in the foreground (non-zero in the mask)
                if mask[y1, x1] > 0 and mask[y2, x2] > 0:
                    # Calculate the angle between the lines
                    angle = np.degrees(np.arctan2(y2 - y1, x2 - x1))
                    
                    # Draw lines in red if the angle is less than 90 degrees
                    if abs(angle) < 90:
                        cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)

# Display the result
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()


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

eimct9ow

eimct9ow1#

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

相关问题