python+opencv寻找图像中类似长方形并计算图形面积周长和中心点
import cv2
def detect_rectangle(image_path):
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
area = cv2.contourArea(contour)
if area < 100:
continue
perimeter = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.02 * perimeter, True)
if len(approx) == 4:
M = cv2.moments(approx)
center_x = int(M["m10"] / M["m00"])
center_y = int(M["m01"] / M["m00"])
cv2.circle(image, (center_x, center_y), 5, (0, 255, 0), -1)
cv2.imshow("Result", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
detect_rectangle("image.jpg")