This is an interesting problem. I cannot offer a satisfying solution, but maybe it is helpful though.
The striking feature of your sample images is that the focus lies on the foreground, while the background - which is to be removed - is unsharp. This is the basis of my approach.
So I first tried something using Fouriertransform, but then I discovered that RidgeFilter
is doing the job.
(For this demo I am working with downsized images. When working on bigger images, probably some parameters need to be adjusted.)
img0 = Import[
"https://community.wolfram.com/c/message_boards/get_message_\
attachment?messageId=1733676&attachment=adult-bangkok-businessmen-\
1571877.jpg"];
img1c = ImageResize[img0, 1000];
img1g = ColorConvert[img1c, "Grayscale"];
img1gs = Sharpen[img1g];
rfImg = DeleteSmallComponents[Binarize[RidgeFilter[img1gs], .02], 500]
From this - using MorphologicalComponents
- it easy to create a "background mask":
morphComp = MorphologicalComponents[ColorNegate@Dilation[rfImg, 1]];
bgNumber = First[Commonest@Flatten[morphComp]];
bgMask = Erosion[ImageApply[If[# == bgNumber, 0, 1] &, Image[morphComp]], 2]
The result is an image with transparent background ...
resultImg = RemoveBackground[bgMask img1c]
... so an arbitrary background can be chosen:
testImg = ExampleData[{"TestImage", "House2"}];
ImageCompose[ImageResize[testImg, ImageDimensions[resultImg]], resultImg]
In case of the first image things do not work that well. But in particular small and critical parts (e.g. the hairs in the wind) can perfectly be separated (using a blue background here as an example):
ImageApply[If[# == {0, 0, 0}, {0, 0, 1}, #] &, rfImg img1c]
Hope that helps a bit, regards -- Henrik