gpt4 book ai didi

python-3.x - 如何找到轮廓的坐标并进行裁剪?

转载 作者:行者123 更新时间:2023-12-02 17:41:56 25 4
gpt4 key购买 nike

我试图找出具有最大面积的轮廓,获取矩形区域的坐标并裁剪出该区域并显示。
ocean.jpg

这是代码:

    import cv2
import numpy as np

img = cv2.imread('ocean.jpg')

gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh=cv2.threshold(gray,127,255,0)
x,contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]

cv2.drawContours(img,contours,-1,(0,255,0),1)
cv2.imshow('Contours',img)
a=[]
for i in range (len(contours)):
a.append(cv2.contourArea(contours[i]))
z=(max(a))
print (contours[a.index(z)])

最佳答案

largestContourArea = 0
largestContour = 0
for cnt in contours:
contourArea = cv2.contourArea(cnt)
if( contourArea > largestContourArea):
largestContour = cnt
largestContourArea = contourArea

# This finds the bounding rectangle
# x,y are the co-ordinates of left-top point and w,h are width and height respectively
x,y,w,h = cv2.boundingRect(largestContour)

# This is simple slicing to get the "Region of Interest"
ROI = img[y:y+h,x:x+w]
cv2.namedWindow("Largest Contour",cv2.WINDOW_NORMAL)
cv2.imshow("Largest Contour",ROI)
cv2.waitKey(0)

关于python-3.x - 如何找到轮廓的坐标并进行裁剪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43368565/

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