ok, no problem. I can do this…
import sys
import cv2
import numpy as np
n = len(sys.argv)
test = '...\Simulation\Scan.bmp' #sys.argv[1]
outputPath = '...\Simulation'
#sys.argv[2]
# load image
img = cv2.imread(test)
# convert to graky
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# threshold input image as mask
mask = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)[1]
# negate mask
mask = 255 - mask
# apply morphology to remove isolated extraneous noise
# use borderconstant of black since foreground touches the edges
kernel = np.ones((3,3), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
# anti-alias the mask -- blur then stretch
# blur alpha channel
mask = cv2.GaussianBlur(mask, (0,0), sigmaX=2, sigmaY=2, borderType = cv2.BORDER_DEFAULT)
mask = (2*(mask.astype(np.float32))-255.0).clip(0,255).astype(np.uint8)
# put mask into alpha channel
result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:, :, 3] = mask
#make mask of where the transparent bits are
trans_mask = result[:,:,3] == 0
#replace areas of transparency with white
result[trans_mask] = [255, 255, 255, 255]
#new image without alpha channel...
new_img = cv2.cvtColor(result, cv2.COLOR_BGRA2BGR)
# Find contours
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
c = max(cnts, key=cv2.contourArea)
cv2.drawContours(new_img, [c], -1, (255, 0, 0), 5)
cv2.circle(new_img, left, 8, (0, 50, 255), 15)
cv2.circle(new_img, right, 8, (0, 255, 255), 15)
cv2.circle(new_img, top, 8, (255, 50, 0), 15)
cv2.circle(new_img, bottom, 8, (255, 255, 0), 15)
# save resulting masked image
cv2.imwrite('test.jpg', new_img)
# display result, though it won't show transparency
##cv2.imshow("output", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
The result ist that:
Problems:
- The quality of background removal is not the best.
- The contour is only on the left side. Sure, i did the code accordingly, but i don’t know how to change, that it is on both feet.
- The contour quality is also not the best.
I hope someone can give me some ideas.
BR/ Dominik