open cv cv2.imread 一张灰度图像素值

问题描述 投票:0回答:1

我正在尝试使用

cv2.imread
加载灰度图像以进一步提取斑点。首先,我有一个图像(如下所示),黑色像素的值(通常在 0 到 1 之间)和白色像素的值为 0.

我想将此图像重新采样为二进制 0(白色像素)和 1(黑色像素),以便使用 cv2 对其执行 blob 提取。然而,我得到的 blob 提取返回 0 个 blob 实例,即使我概括了搜索参数。

查看图像直方图后,我发现我实际上没有二值图像。下面我将包括用于读入、重新分类、设置 blob 参数并尝试检测 blob 的代码。

图片链接:tif_file

重新分类:

import cv2
import numpy as np
import os
from osgeo import gdal
import matplotlib.pyplot as plt
from rasterio.plot import show
import skimage.io

driver = gdal.GetDriverByName('GTiff')
file = gdal.Open("tif_folder/Clip_depth_sink.tif")
band = file.GetRasterBand(1)
lista = band.ReadAsArray()

# reclassification
for j in  range(file.RasterXSize):
    for i in  range(file.RasterYSize):
        if lista[i,j] == 0:
            lista[i,j] = 0
        elif lista[i,j] != 0:
            lista[i,j] = 1
        else:
            lista[i,j] = 2

## create new file
binary_sinks = driver.Create('tif_folder\\clipped_binary_sinks.tif', file.RasterXSize , file.RasterYSize , 1)
binary_sinks.GetRasterBand(1).WriteArray(lista)

# spatial ref system
proj = file.GetProjection()
georef = file.GetGeoTransform()
binary_sinks.SetProjection(proj)
binary_sinks.SetGeoTransform(georef)
binary_sinks.FlushCache()

重新分类的图像直方图:

image = cv2.imread('tif_folder\\clipped_binary_sinks.tif', -1)

plt.hist(image, bins=10, range=(-1,3))

斑点检测:

image = cv2.imread('tif_folder\\clipped_binary_sinks.tif',-1)

plt.hist(image, bins=10, range=(-1,3))

#set blob parameters to look for
params = cv2.SimpleBlobDetector_Params()

params.filterByArea = True
params.minArea = 9
params.maxArea = 1000

params.filterByCircularity = True
params.minCircularity = 0.5

#create the detector out of the parameters
detector = cv2.SimpleBlobDetector_create(params)

#extract the blobs from the image
keypoints = detector.detect(image)
print(len(keypoints))

有几件事让我感到困惑。例如,虽然图像像素值在重新分类后应该落在 0 和 1 附近,但它们似乎落入了不完全等于 0 和 1 的区间,正如我们在直方图中看到的那样。正如我之前所说,open cv 没有检测到斑点,这可能是有道理的,因为尽管相邻像素的值接近,但根据直方图,它们略有偏差。

是否有更好的方法将图像重新分类为二进制来解决这个问题? 我还遗漏了另一个导致 blob 检测不可行的问题吗?

提前致谢!

python opencv blob arcgis resampling
1个回答
0
投票

您可以像这样更简单地对图像进行分类:

import numpy as np
import cv2

# Load float image
im = cv2.imread('Clip_depth_sink.tif', cv2.IMREAD_UNCHANGED)

# Make solid black classified image, uint8 is plenty for 3 values
classified = np.zeros(im.shape, np.uint8)

# Set everything above a low threshold to 127
classified[im>0.001] = 127

# Set everything above a high threshold to 255
classified[im>0.999] = 255

# Count pixels in each class
print(np.unique(classified, return_counts=True))

# Save result
cv2.imwrite('result.png', classified)

输出

(array([  0, 127, 255], dtype=uint8), array([3647448,  131186,    1878]))

表示有 3647448 个黑色像素 (0)、131186 个中灰色 (127) 和 1878 个白色 (255) 像素


请注意,您可以通过在前面放置波浪号来简单地将反转图像传递给斑点检测器:

blobs = BlobDetector(~classified)
© www.soinside.com 2019 - 2024. All rights reserved.