python 如何应用阈值算子突出显示最大对象

snz8szmq  于 2023-05-27  发布在  Python
关注(0)|答案(1)|浏览(120)

我想知道如何应用阈值运算符来突出显示最大的对象,这是我输出的第3列。
使用此代码,我将使用np.hstack()比较3个图像。img_hubble是原始图像,dst是模糊图像。

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

# get image
img_hubble = cv2.imread("hubble.png", 0)

# define the kernel size
kernel = np.ones((15,15), np.float32)/225
dst = cv2.filter2D(img_hubble, -1, kernel)

#applying threshhold operator  to highlight the largest object
thresh = cv2.threshold(dst, 0, 255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

result = np.hstack((img_hubble,dst,thresh))
cv2.imshow('result',thresh )

cv2.waitKey()
cv2.destroyAllWindows()

输出下面的图像。

上面的代码给予了我以下错误:

OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'imshow'
> Overload resolution failed:
>  - mat is not a numerical tuple
>  - Expected Ptr<cv::cuda::GpuMat> for argument 'mat'
>  - Expected Ptr<cv::UMat> for argument 'mat'
bvn4nwqk

bvn4nwqk1#

我已经清理了剧本,并试图解决我认为你的问题。
Threshold返回2个参数、阈值集和实际的二进制图像:

_, thresh = cv2.threshold(dst, 0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

抓取二进制图像,同时忽略阈值。
阈值化只会返回保留亮像素组的二进制图像。它不会返回单个最大的亮像素组。
连接的组件或标签需要用于此。这里有一个解决方案:

# labels the threshold image and get stats.
n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh)

# get areas from stats
areas = stats[:,-1]

# find the second largest area (Assuming the largest is always the background)
index_largest_component = np.argsort(areas)[-2]
cv2.imshow('result',(labels==index_largest_component).astype(np.float32))

这将过滤您的阈值图像,仅显示最大的亮像素组。
代码如下:

import cv2
import numpy as np

# get image
img_hubble = cv2.imread("hubble.jpg", cv2.IMREAD_GRAYSCALE)

# define the kernel size
kernel = np.ones((15,15), np.float32)/225
dst = cv2.filter2D(img_hubble, -1, kernel)

# applying threshhold operator  to highlight the largest object
_, thresh = cv2.threshold(dst, 0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

# stack resulting images
result = np.hstack((img_hubble,dst,thresh))

# labels the threshold image and get stats.
n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh)

# get areas from stats
areas = stats[:,-1]

# find the second largest area (Assuming the largest is always the background)
index_largest_component = np.argsort(areas)[-2]

# show stack and largest area
cv2.imshow('res',result)
cv2.imshow('result',(labels==index_largest_component).astype(np.float32))

cv2.waitKey()
cv2.destroyAllWindows()

相关问题