import cv2
import numpy as np
#Load the image
img = cv2.imread('cubeedge.png', cv2.IMREAD_GRAYSCALE)
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
#Find the contours in the binary image
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#Find the largest contour (i.e. the edge of the cube)
largest_contour = max(contours, key=cv2.contourArea)
#Create a mask for the largest contour
mask = np.zeros(img.shape, dtype=np.uint8)
cv2.drawContours(mask, [largest_contour], -1, (255, 255, 255), thickness=cv2.FILLED)
#Apply the mask to the original image to isolate the edge
masked_image = cv2.bitwise_and(img, mask)
#Find the minimum and maximum y-coordinates of the edge
min_y = np.min(largest_contour[:, 0, 1])
max_y = np.max(largest_contour[:, 0, 1])
#Calculate the average y-coordinate and draw a horizontal line at that position
y_pos = int((min_y + max_y) / 2)
cv2.line(img, (0, y_pos), (img.shape[1], y_pos), (255, 0, 0), thickness=2)
#Apply Gaussian blur to remove noise
blur = cv2.GaussianBlur(img, (5,5), 0)
#Apply Canny edge detection
edges = cv2.Canny(blur, 50, 150)
#Apply Hough transform to detect lines
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
#Extract the first detected line
rho, theta = lines[0][0]
#Convert theta to degrees and subtract 90 to get the angle with respect to the horizontal
angle = np.rad2deg(theta) - 90
cv2.namedWindow('Result', cv2.WINDOW_NORMAL)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
#Print the angle
print("Angle: ", angle)
我尝试使用等高线绘图,但它在图像的中心而不是立方体的边缘绘制了一条水平线。我还想描绘出边缘而不是在那一点画一条合适的水平线。我想描绘出立方体的边缘并找到它与水平面之间的角度。