Currently I am trying to get rid of all background noises from my images.
I'm pretty sure I have to use some kind of Dilation or Erosion algorithm but I also like to achieve coding the filter routine in Swift.
This is my unfiltered noisy image:
And this could be what It should look like after applying the filter:
Note: Using openCV the code should look maybe like this (but like I'd mentioned- I'd like to use Swift instead):
img = cv2.imread("img.png")
bggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
labelnum, labelimg, contours, GoCs = cv2.connectedComponentsWithStats(bggray)
for label in xrange(1, labelnum):
x,y,w,h,size = contours[label]
if size <= 50:
img[y:y+h, x:x+w] = 0
cv2.imwrite("img.png", img)
Note: This is the Swift code I got so far but it is obviously not working this way:
class CleanupFilter: CIFilter {
var inputImage : CIImage?
var threshold1: Float = 0.5
var threshold2: Float = 0.7
var thresholdKernel = CIColorKernel(source:
"kernel vec4 thresholdKernel(sampler image, float threshold1, float threshold2) {" +
"vec4 pixel = sample(image, samplerCoord(image));" +
"const vec3 rgbToIntensity = vec3(0.114, 0.587, 0.299);" +
"float intensity = dot(pixel.rgb, rgbToIntensity);" +
"if (intensity < threshold1) {return vec4(0, 0, 0, 0)}" +
"if (intensity < threshold1 && intensity > threshold2) {return vec4(1, 1, 1, 1)}" +
"else {return vec4(0, 0, 0, 0)}" + "}")
override var outputImage: CIImage! {
guard let inputImage = inputImage,
let thresholdKernel = thresholdKernel else {
return nil
}
let extent = inputImage.extent
let arguments : [Any] = [inputImage, threshold1, threshold2]
return thresholdKernel.apply(extent: extent, arguments: arguments)
}
}
Any help how to edit thresholdKernel to achieve a working filter routine would be very appreciated.