如何在OpenCV中的阈值操作中使用循环

时间:2019-08-31 02:06:23

标签: 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, imageG, imageR:
        th, dst = cv2.threshold(img, thresh, maxValue, cv2.THRESH_BINARY)
        #print(dst.shape)
        #print(len(dst))
        plt.imshow(dst)

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

2 个答案:

答案 0 :(得分:3)

在您显示的代码中,您正在将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')

制作:

enter image description here

答案 1 :(得分:2)

您可以将figure与子图一起使用,如下所示:

fig = plt.figure()

step = 51
maxValue = 255
nrows = 3
ncols = maxValue // step

i = 1
for thresh in range(0, maxValue, step):
    for img in imageB, imageG, imageR:
        th, dst = cv2.threshold(img, thresh, maxValue, cv2.THRESH_BINARY)
        fig.add_subplot(nrows, ncols, i)
        plt.imshow(dst)
        i = i + 1

关于您的问题为什么我打印(len(dst))时它仅返回图像中行的长度?,例如参见this question