<p>您不需要删除最后一个元素,您可以从末尾获取第二个元素</p>
<ul>
<li><code>c=sorted(cnts, key=cv2.contourArea)</code>的结果不是一个NumPy数组,而是一个<strong>列表<strong><br/>
您可以使用<code>type(c)</code>检查类型,结果是<code><class 'list'></code>。<br/>
您可以使用<code>del</code>:<code>del c[-1]</code>删除最后一个元素,但不必这样做</李>
<li>使用:<code>c = c[-2]</code>提取列表的最后一个元素。<br/>
现在<code>type(c)</code>是<code><class 'numpy.ndarray'></code></李>
<li>使用<code>extLeft = c[:, :, 0].min()</code>和<code>extRight = c[:, :, 0].max()</code>查找最小值和最大值</李>
</ul>
<p>代码如下:</p>
<pre><code>import imutils
import cv2
import numpy as np
image = cv2.imread(r"SimpleBoxTest.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c=sorted(cnts, key=cv2.contourArea)
#c = np.delete(c, (-1), axis=0)
# c is a list, and not a numpy array, so use del instead of np.delete
# But why?
# del c[-1]
# Get one element before the last element in the list
c = c[-2] # Now c is a numpy.ndarray
extLeft = c[:, :, 0].min()
extRight = c[:, :, 0].max()
extTop = c[:, :, 1].min()
extBot = c[:, :, 1].max()
# Draw rectangle for testing
cv2.rectangle(image, (extLeft, extTop), (extRight, extBot), (0, 255, 0))
cv2.imshow("image", image)
cv2.waitKey()
cv2.destroyAllWindows();
</code></pre>
<hr/>
<h2>更新:</h2>
<p>如果需要找到的所有等高线中的第二个极值点,可以在<code>c</code>中迭代等高线:</p>
<pre><code># Mark all contours with red:
cv2.drawContours(image, cnts, -1, (0, 0, 255), thickness=5)
# Delete last element of the list
del c[-1]
# Initialize:
extLeft, extRight, extTop, extBot = 1e9, -1e9, 1e9, -1e9
# Iterate list and find the extreme points
for cc in c:
extLeft = min(cc[:, :, 0].min(), extLeft)
extRight = max(cc[:, :, 0].max(), extRight)
extTop = min(cc[:, :, 1].min(), extTop)
extBot = max(cc[:, :, 1].max(), extBot)
# Draw rectangle for testing
cv2.rectangle(image, (extLeft, extTop), (extRight, extBot), (0, 255, 0), thickness=5)
</code></pre>
<hr/>
<p>不使用for循环的解决方案:</p>
<ul>
<li>您可以使用<code>np.vstack(c)</code>连接列表中的NumPy数组。<br/>
然后找到连接数组中的极值点</李>
</ul>
<p>代码:</p>
<pre><code># Delete last element of the list.
del c[-1]
# Concatenate arrays along vertical axis.
c = np.vstack(c)
# Find extreme points:
extLeft = c[:, :, 0].min()
extRight = c[:, :, 0].max()
extTop = c[:, :, 1].min()
extBot = c[:, :, 1].max()
</code></pre>
<hr/>
<p>结果:<br/>
<a href="https://i.stack.imgur.com/jee8A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jee8A.png" alt="enter image description here"/></a></p>