gpt4 book ai didi

python - 求矩形区域的中心线和中心点

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:23 24 4
gpt4 key购买 nike

我运行了以下代码来创建一个矩形轮廓:

#import the necessary packages
import argparse
import imutils
import cv2
import numpy as np

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to the input image")
args = vars(ap.parse_args())

# load the image, convert it to grayscale, blur it slightly, and threshold it
image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)

# threshold the image, then perform a series of erosions + dilations to remove any small regions of noise
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=2)

contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# Find the index of the largest contour
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt=contours[max_index]

x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)

# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)

我想找到矩形轮廓的中心线和中心点。请指教。

最佳答案

因为您已经使用 x,y,w,h = cv2.boundingRect(cnt) 获得所需轮廓的 (x, y, w, h)上面的代码,所以垂直中线的中心可以由 (x+w//2, y+h//2) 给出,垂直线可以使用下面的代码绘制:

x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
# center line
cv2.line(image, (x+w//2, y), (x+w//2, y+h), (0, 0, 255), 2)
# below circle to denote mid point of center line
center = (x+w//2, y+h//2)
radius = 2
cv2.circle(image, center, radius, (255, 255, 0), 2)

输出:

enter image description here

关于python - 求矩形区域的中心线和中心点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57190197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com