使用openCV库和python检测图像中的5条最佳线?

dy1byipe  于 2022-12-27  发布在  Python
关注(0)|答案(2)|浏览(173)

我尝试使用Hough变换来确定给定图像(作为参数)中质量和长度最好的5条线。下面的代码标记了它在图像中检测到的线(如果它是一个相对简单的图像)。我如何让他只标记最好的k条线?

import sys
import math
import cv2 as cv
import numpy as np
import sys
import numpy as np
from matplotlib import pyplot as plt

def main(argv):
    default_file = "path to image"
    filename = argv[0] if len(argv) > 0 else default_file
    # Loads an image
    src = cv.imread(cv.samples.findFile(filename), cv.IMREAD_GRAYSCALE)
    # Check if image is loaded fine
    if src is None:
        print('Error opening image!')
        print('Usage: hough_lines.py [image_name -- default ' + default_file + '] \n')
        return -1

    #edge detection
    dst = cv.Canny(src, 50, 200, None, 3)

    # Copy edges to the images that will display the results in BGR
    cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
    cdstP = np.copy(cdst)

    lines = cv.HoughLines(dst, 1, np.pi / 180, 150, None, 0, 0)

    if lines is not None:
        for i in range(0, len(lines)):
            rho = lines[i][0][0]
            theta = lines[i][0][1]
            a = math.cos(theta)
            b = math.sin(theta)
            x0 = a * rho
            y0 = b * rho
            pt1 = (int(x0 + 1000 * (-b)), int(y0 + 1000 * (a)))
            pt2 = (int(x0 - 1000 * (-b)), int(y0 - 1000 * (a)))
            cv.line(cdst, pt1, pt2, (0, 0, 255), 3, cv.LINE_AA)

    linesP = cv.HoughLinesP(dst, 1, np.pi / 180, 50, None, 50, 10)

    if linesP is not None:
        for i in range(0, len(linesP)):
            l = linesP[i][0]
            cv.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0, 0, 255), 3, cv.LINE_AA)

    cv.imshow("Source", src)
    #cv.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst)
    cv.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP)

    cv.waitKey()
    return 0

if __name__ == "__main__":
    main(sys.argv[1:])

我试图检测图像中的最佳k线

3vpjnl9f

3vpjnl9f1#

我不知道,但你可以试试

import cv2
import numpy as np

img = cv2.imread("image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

lines = cv2.HoughLinesP(gray, 1, np.pi/180, 50, None, 50, 10)

# Sort lines based on length
lines = sorted(lines, key=lambda x: cv2.norm(x[0]))

k = 5
lines = lines[:k]

for line in lines:
    x1, y1, x2, y2 = line[0]
    cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 3)

cv2.imshow("Image with best k lines", img)
cv2.waitKey()
vaqhlq81

vaqhlq812#

这里是OpenCv4.6.0的最新版本

import cv2
import numpy as np

# Load the image and convert it to grayscale
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Compute the Hough Transform
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)

# Calculate the length of each line
lengths = []
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))

        line_length = np.sqrt((x2-x1)**2 + (y2-y1)**2)
        lengths.append(line_length)

# Sort the lines in descending order of length
sorted_lines = sorted(lines, key=lambda line: lengths[lines.index(line)], reverse=True)

# Mark the best k lines
k = 5
for line in sorted_lines[:k]:
    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))

        cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 2)

# Show the image
cv2.imshow("Lines", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

相关问题