Reputation: 1
I've been trying to write a script in opencv for some greyscale image processing. However, I keep running into an issue when finding and drawing contours on thresholded images. Finding contours is easy and gives me the kind of result that I'm looking for. But, when I choose the largest contour by area and intend to draw it seperately, I get a much more 'broken up' result. I've been trying to figure out what is wrong with my code that results in this for a while now, but frankly can't figure it out. Anybody else have a similar experience or possible solution?
My (admittedly very messy) current code is:
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
import os
import math as m
import imutils as imt
read_directory = r'E:\Other\Ultrasound_Trad_Alg\Input'
write_directory = r'E:\Other\Ultrasound_Trad_Alg\Output'
os.chdir(read_directory)
image_files = os.listdir(read_directory)
for image_file in image_files:
input_image_grey = cv.imread(image_file,0)
input_image_color = cv.imread(image_file)
input_image_color_2 = input_image_color.copy()
#Initial Black Background Masking Process:
blurred_input = cv.GaussianBlur(input_image_grey,(7,7),0)
_,thresholded_image_binary = cv.threshold(blurred_input,0,255,cv.THRESH_BINARY)
input_contours,hierarchy = cv.findContours(thresholded_image_binary,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
chosen_input_contour = max(input_contours, key=cv.contourArea)
input_mask = np.zeros_like(input_image_grey)
cv.drawContours(input_mask, chosen_input_contour, -1, 255, -1)
#For Testing and Visualization:
cv.drawContours(input_image_color, chosen_input_contour, -1, (0,255,0), 1)
cv.drawContours(input_image_color_2, input_contours, -1, (0,255,0), 1)
cv.imshow("test1",thresholded_image_binary)
cv.imshow("test2",input_image_color)
cv.imshow("test3",input_image_color_2)
cv.imshow("mask",input_mask)
print(cv.isContourConvex(chosen_input_contour))
print(cv.contourArea(chosen_input_contour))
cv.waitKey(0)
When I run this code, I get the following set of 4 images just to demonstrate what I am talking about:
https://i.sstatic.net/IP7Ip.jpg
As can be seen, the initial set of contours are pretty much exactly what I'm looking for. However, by isolating the largest contour in the image and drawing it separately, I get a broken up contour that does not work for me. I've also checked the contour areas and it shows that I should have exactly 5, meaning there shouldn't be any tiny hidden contours messing with results either. Any thoughts on what is happening?
Upvotes: 0
Views: 271
Reputation: 53164
I think your issue in your Python/OpenCV code is that you have:
input_mask = np.zeros_like(input_image_grey)
and it should be
input_mask = np.zeros_like(thresholded_image_binary)
the binary mask needs to be the same bit-depth as your binary image, not your grayscale image. That is it needs to be 1-bit and not 8-bits.
See if that fixes it.
Upvotes: 1