gpt4 book ai didi

python - 如何使用 OpenCV 仅获取图像中的中心对象?

转载 作者:行者123 更新时间:2023-12-04 08:21:53 25 4
gpt4 key购买 nike

我试图通过使用连接的 cv2.connectedComponentsWithStats 仅获得此图像中的中心重绕。但是我不知道如何只获得中心图像。
enter image description here
我的尝试是这样的:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, bw = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

img = cv2.threshold(bw, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary
def undesired_objects(image):
image = image.astype('uint8')
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4)
sizes = stats[:, -1]

max_label = 1
max_size = sizes[1]
for i in range(2, nb_components):
if sizes[i] > max_size:
max_label = i
max_size = sizes[i]

img2 = np.zeros(output.shape)
img2[output == max_label] = 255
cv2.imshow("Biggest component", img2)
cv2.waitKey()

undesired_objects(img)

最佳答案

我认为你应该在使用 connectedComponentsWithStats 之前更好地处理你的图像

import cv2
import numpy as np


def threshold_gray_const(image_, rang: tuple):
return cv2.inRange(image_, rang[0], rang[1])


def reject_borders(image_):
out_image = image_.copy()
h, w = image_.shape[:2]
for row in range(h):
if out_image[row, 0] == 255:
cv2.floodFill(out_image, None, (0, row), 0)
if out_image[row, w - 1] == 255:
cv2.floodFill(out_image, None, (w - 1, row), 0)
for col in range(w):
if out_image[0, col] == 255:
cv2.floodFill(out_image, None, (col, 0), 0)
if out_image[h - 1, col] == 255:
cv2.floodFill(out_image, None, (col, h - 1), 0)
return out_image


img = cv2.imread("D:\\Downloads\\ZXo3i.png")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# ret, bw = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
#
# img = cv2.threshold(bw, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary
img = threshold_gray_const(gray, (240, 255))
img = reject_borders(img)


def undesired_objects(image):
image = image.astype('uint8')

nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4)
sizes = stats[:, -1]

max_label = 1
max_size = sizes[1]
for i in range(2, nb_components):
if sizes[i] > max_size:
max_label = i
max_size = sizes[i]

img2 = np.zeros(output.shape)
img2[output == max_label] = 255
cv2.imshow("Biggest component", img2)
cv2.waitKey()


undesired_objects(img)

关于python - 如何使用 OpenCV 仅获取图像中的中心对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65457510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com