Python 如何在OpenCV中使用loop进行阈值运算

Python 如何在OpenCV中使用loop进行阈值运算,python,opencv,matplotlib,Python,Opencv,Matplotlib,我想对几个具有不同阈值的灰度图像应用阈值操作,以便输出(显示为matplotlib绘图)将是15个左右不同的图像,每个图像应用阈值级别。我面临的问题是,它运行后只显示一个图像,但如果我在循环中说print(dst.shape),它将打印15个图像形状 我已尝试将输出dst放入列表中,以便通过索引dst[2]访问它们,但这返回了一个错误 maxValue = 255 dst = [] for thresh in range(0, 255, 51): for img in imageB, i

我想对几个具有不同阈值的灰度图像应用阈值操作,以便输出(显示为matplotlib绘图)将是15个左右不同的图像,每个图像应用阈值级别。我面临的问题是,它运行后只显示一个图像,但如果我在循环中说
print(dst.shape)
,它将打印15个图像形状

我已尝试将输出
dst
放入列表中,以便通过索引
dst[2]
访问它们,但这返回了一个错误

maxValue = 255
dst = []
for thresh in range(0, 255, 51):
    for img in imageB, imageG, imageR:
        th, dst = cv2.threshold(img, thresh, maxValue, cv2.THRESH_BINARY)
        #print(dst.shape)
        #print(len(dst))
        plt.imshow(dst)

我试图从循环中获得15个不同的图像。这是matplotlib问题吗?我是否需要创建一个特定大小的图形,然后访问
dst
列表中的每个变量?如果是这样,为什么当I
print(len(dst))
只返回图像中行的长度呢?

您可以使用带有子图的
图形,如下所示:

fig=plt.figure()
步骤=51
最大值=255
nrows=3
ncols=maxValue//step
i=1
对于范围内的阈值(0,最大值,步长):
对于imageB、imageG、imageR中的img:
th,dst=cv2.阈值(img,thresh,maxValue,cv2.thresh_二进制)
图add_子批次(nrows、ncols、i)
plt.imshow(dst)
i=i+1

关于您的问题,为什么当我打印(len(dst))时,它只返回图像中行的长度?例如,请参阅。

在您显示的代码中,您正在将阈值图像从
cv2.threshold()
分配给列表的名称,因此
print(len(dst))
返回有关图像长度而不是列表长度的信息。您已经有效地用图像覆盖了列表

在循环中绘制阈值图像:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Make a test image.
r = np.random.randint(0,255,10000).reshape(100,100)
g = np.random.randint(0,255,10000).reshape(100,100)
b = np.random.randint(0,255,10000).reshape(100,100)
img = np.dstack([r,g,b]).astype(np.uint8)

# Convert test image to grayscale.
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

fig, axs = plt.subplots(1,3, figsize=(6,2))
for thresh_value, ax in zip(range(75,255,75), axs.ravel()):
    T, thresh = cv2.threshold(img_gray, thresh_value, 255, cv2.THRESH_BINARY)
    ax.imshow(thresh, cmap='gray')
    ax.set_title(str(thresh_value))

plt.tight_layout()
plt.savefig('plot_img.png')
制作:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Make a test image.
r = np.random.randint(0,255,10000).reshape(100,100)
g = np.random.randint(0,255,10000).reshape(100,100)
b = np.random.randint(0,255,10000).reshape(100,100)
img = np.dstack([r,g,b]).astype(np.uint8)

# Convert test image to grayscale.
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

fig, axs = plt.subplots(1,3, figsize=(6,2))
for thresh_value, ax in zip(range(75,255,75), axs.ravel()):
    T, thresh = cv2.threshold(img_gray, thresh_value, 255, cv2.THRESH_BINARY)
    ax.imshow(thresh, cmap='gray')
    ax.set_title(str(thresh_value))

plt.tight_layout()
plt.savefig('plot_img.png')

非常好
fig,axs=plt。子批次(1,3,figsize=(6,2))
有助于解决我将研究的下一个问题,即如何在循环时设置子批次位置。反应很好!下面的
plt.show()
有什么用?看起来好像
plt.imshow(dst)
完成了这个任务,是吗?而且,这是一种非常有帮助的方法,也是非常有帮助的回应。我将更深入地了解numPy数组,因为我需要更多关于这方面的知识才能更有效地使用OpenCV。@DavidAlford,你说得对,last
show()
并不是真的需要。