opencv 组合2个阈值图像以获得此效果

ssgvzors  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(145)

我有以下2个图像:

如何组合图像以获得这2张图像中的任何一张?

我的代码:

import cv2
import numpy as np

image = cv2.imread('skadi.png')
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
cv2.imshow('greyscale',gray)
_, binary = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
cv2.imshow('treshold',binary)
binary= 255 - binary
cv2.imshow('inverted',binary)
kernel = np.ones((25, 25), np.uint8)
closing = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
cv2.imshow('closing',closing)
#closing = 255-closing
closing2 =  cv2.bitwise_not(closing)
cv2.imshow('invetedclosing',closing2)
result = cv2.bitwise_or(closing, closing2)
cv2.imshow('convned',result)
edges = cv2.Canny(result, 100, 200)

cv2.waitKey(0)
cv2.destroyAllWindows()

我试着将它们与cv2.bitwise_orcv2.bitwise_xor结合起来,但最终以白色屏幕结束。
任何帮助感激不尽!

j9per5c4

j9per5c41#

这是一个简单的脚本,它可以提取二值图像中最大的白色斑点。因为图像中最大的白色斑点是前景(也是你要找的形状),所以这应该会给予你预期的结果。
它基本上得到了所有的外部轮廓,并保留了面积最大的轮廓。然后在一张新的图像上绘制它。
这是源代码,我使用this图像,因为你没有提供原始.

# Imports:
import cv2
import numpy as np

# image path
path = "D://opencvImages//"

# Reading an image in default mode:
inputImage = cv2.imread(path + "testBlob.png")

# Grayscale conversion:
grayscaleImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)

# Threshold via Otsu:
# Note the image inversion:
_, binaryImage = cv2.threshold(grayscaleImage, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# Store a copy of the input image:
biggestBlob = binaryImage.copy()
# Set initial values for the
# largest contour:
largestArea = 0
largestContourIndex = 0

# Find the contours on the binary image:
contours, hierarchy = cv2.findContours(binaryImage, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

# Get the largest contour in the contours list:
for i, cc in enumerate(contours):
    # Find the area of the contour:
    area = cv2.contourArea(cc)
    # Store the index of the largest contour:
    if area > largestArea:
        largestArea = area
        largestContourIndex = i

# Once we get the biggest blob, paint it black:
tempMat = binaryImage.copy()
cv2.drawContours(tempMat, contours, largestContourIndex, (0, 0, 0), -1, 8, hierarchy)

# Erase smaller blobs:
biggestBlob = biggestBlob - tempMat

# Show the result:
cv2.imshow("biggestBlob", biggestBlob)
cv2.waitKey(0)

这就是结果:

相关问题