如何在 OpenCV Python 中更改轮廓的边界矩形值?
How to change bounding rect values of contour in OpenCV Python?
我想更改下一个轮廓的宽度值。我尝试这样做,但事实证明它仍然保留了轮廓的原始值。我该怎么做呢?提前谢谢你。
更新:这是我正在处理的实际代码。
temp = 0; #Holds the last element we iterated replaced value
for i,c in enumerate(contours2):
[x, y, w, h] = cv2.boundingRect(contours2[i])
if i in percentiles: #if the current index is in the percentiles array
[i, j, k, l] = cv2.boundingRect(contours2[temp]) #Get contour values of element to overwrite
k = (x+w)-i
temp=i+1;
#DRAW
for c in contours2: #when I draw it the k value of the overwritten elements doesn't change,why?
[x, y, w, h] = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
这里有一个误解,纯粹是Python,与OpenCV无关。检查以下代码:
>>> a = 5
>>> b = a
>>> a = 7
>>> a
7
>>> b
5
当我设置 b = a
时,我将 b
设置为与 a
具有相同的 当前值 ,但我实际上并没有为 a
创建一个新的 name。这意味着以后如果我更改 a
的值,它不会影响 b
的值。这是相关的,因为在您的代码中,您正在编写:
[i, j, k, l] = cv2.boundingRect(contours2[temp])
k = (x+w)-i
好像这修改了轮廓。它没有;它只是修改了变量k
。你只是在循环的每次迭代中覆盖 k
。
此外,边界框与轮廓不是一回事。轮廓根本没有改变,因为您没有修改 contours2
变量。您需要知道您是否真的想要边界框或轮廓。轮廓是勾勒出轮廓形状的点列表。边界框就是适合轮廓点的最小尺寸 vertical/horizontal 框。如果要获取边界框并对其进行修改,则应将边界框 store 到变量中;特别是,如果您要存储多个边界框,您会希望将它们存储到一个列表中。例如:
bounding_boxes = []
for c in contours2:
[x, y, w, h] = cv2.boundingRect(c)
bounding_boxes.append([x, y, w, h])
这将为您提供一个列表,其中第 i
个元素是第 i
个轮廓周围的边界框。如果您想修改存储的边界框,只需在将其附加到列表之前执行即可:
bounding_boxes = []
for c in contours2:
[x, y, w, h] = cv2.boundingRect(c)
w = w*2
bounding_boxes.append([x, y, w, h])
我不完全清楚你的代码应该做什么,所以我不能给你一个固定的版本,但希望这会让你朝着正确的方向前进。
我想更改下一个轮廓的宽度值。我尝试这样做,但事实证明它仍然保留了轮廓的原始值。我该怎么做呢?提前谢谢你。
更新:这是我正在处理的实际代码。
temp = 0; #Holds the last element we iterated replaced value
for i,c in enumerate(contours2):
[x, y, w, h] = cv2.boundingRect(contours2[i])
if i in percentiles: #if the current index is in the percentiles array
[i, j, k, l] = cv2.boundingRect(contours2[temp]) #Get contour values of element to overwrite
k = (x+w)-i
temp=i+1;
#DRAW
for c in contours2: #when I draw it the k value of the overwritten elements doesn't change,why?
[x, y, w, h] = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
这里有一个误解,纯粹是Python,与OpenCV无关。检查以下代码:
>>> a = 5
>>> b = a
>>> a = 7
>>> a
7
>>> b
5
当我设置 b = a
时,我将 b
设置为与 a
具有相同的 当前值 ,但我实际上并没有为 a
创建一个新的 name。这意味着以后如果我更改 a
的值,它不会影响 b
的值。这是相关的,因为在您的代码中,您正在编写:
[i, j, k, l] = cv2.boundingRect(contours2[temp])
k = (x+w)-i
好像这修改了轮廓。它没有;它只是修改了变量k
。你只是在循环的每次迭代中覆盖 k
。
此外,边界框与轮廓不是一回事。轮廓根本没有改变,因为您没有修改 contours2
变量。您需要知道您是否真的想要边界框或轮廓。轮廓是勾勒出轮廓形状的点列表。边界框就是适合轮廓点的最小尺寸 vertical/horizontal 框。如果要获取边界框并对其进行修改,则应将边界框 store 到变量中;特别是,如果您要存储多个边界框,您会希望将它们存储到一个列表中。例如:
bounding_boxes = []
for c in contours2:
[x, y, w, h] = cv2.boundingRect(c)
bounding_boxes.append([x, y, w, h])
这将为您提供一个列表,其中第 i
个元素是第 i
个轮廓周围的边界框。如果您想修改存储的边界框,只需在将其附加到列表之前执行即可:
bounding_boxes = []
for c in contours2:
[x, y, w, h] = cv2.boundingRect(c)
w = w*2
bounding_boxes.append([x, y, w, h])
我不完全清楚你的代码应该做什么,所以我不能给你一个固定的版本,但希望这会让你朝着正确的方向前进。