Reputation: 196
I have the following 2 images:
How could I combine the images to get any of these 2 images?
My code:
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()
I tried combining them wit cv2.bitwise_or
and cv2.bitwise_xor
, but ended with a white screen.
Any help appreciated!
Upvotes: 1
Views: 102
Reputation: 5805
Here's a handy script that basically extracts the biggest white blob in a binary image. Since the biggest white blob in your image is blob is the foreground (and the shape you are looking for), this should give you the expected result.
It basically gets all the external contours and keeps the contour with the biggest area. It then draws it on a new image.
This is the code, I'm using this image, since you did not provide the original.
# 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)
This is the result:
Upvotes: 3