Skip to content

Instantly share code, notes, and snippets.

@alexander-malafeev
Created April 22, 2018 17:40
Show Gist options
  • Select an option

  • Save alexander-malafeev/4f2b3af29808b56507219f22c85c37b4 to your computer and use it in GitHub Desktop.

Select an option

Save alexander-malafeev/4f2b3af29808b56507219f22c85c37b4 to your computer and use it in GitHub Desktop.
# remove-background Often we need to remove monotonous background from the image. However often color of pixels is not exactly uniform due to the compression artifacts. It is expecially critical arund the object. Thus the simple fill won't work. This script takes the color of the top left pixel as a reference one and performs a fill with the whi…
from scipy import misc
import glob
import numpy as np
import sys
#print len(sys.argv)
if len(sys.argv)<3:
print "not enough arguments"
print "try python remove_background.py infile outfile [threshold = 10]"
else:
f_in = sys.argv[1]
f_out = sys.argv[2]+'.bmp'
#for image_path in glob.glob("woman1.png"):
image = misc.imread(f_in)
#print image.shape
#print image.dtype
# define the threshold
# we paint all the pixels which color is within the threshold from the
# top left pixel
if len(sys.argv)==4:
err = int(sys.argv[3])
else:
err = 10
# get the color of top left pixel
first_pixel = [image[0,0,0], image[0,0,1], image[0,0,2]]
fpr = image[0,0,0]
fpg = image[0,0,1]
fpb = image[0,0,2]
#print [fpr, fpg, fpb]
wx = image.shape[1]
wy = image.shape[0]
image_out = image
visited = np.zeros([wy, wx], dtype=bool)
for i in range(wx):
visited[0, i] = 1
for i in range(wx):
visited[wy-1, i] = 1
for i in range(wy):
visited[i, 0] = 1
for i in range(wy):
visited[i, wx-1] = 1
#print np.amax(image)
queue = []
queue.append([1,1])
visited[1][1] = 1
while queue:
node = queue.pop()
y = node[0]
x = node[1]
#print [y,x]
visited[y,x] = 1
image_out[y,x,0]= 255
image_out[y,x,1]= 255
image_out[y,x,2]= 255
if not visited[y, x-1]:
if abs(image[y,x-1,0]-fpr)+abs(image[y,x-1,1]-fpg)+abs(image[y,x-1,2]-fpb)<err:
queue.append([y, x-1])
visited[y, x-1] = 1
if not visited[y, x+1]:
if abs(image[y,x+1,0]-fpr)+abs(image[y,x+1,1]-fpg)+abs(image[y,x+1,2]-fpb)<err:
queue.append([y, x+1])
visited[y, x+1] = 1
if not visited[y-1, x]:
if abs(image[y-1,x,0]-fpr)+abs(image[y-1,x,1]-fpg)+abs(image[y-1,x,2]-fpb)<err:
queue.append([y-1, x])
visited[y-1, x] = 1
if not visited[y+1, x]:
if abs(image[y+1,x,0]-fpr)+abs(image[y+1,x,1]-fpg)+abs(image[y+1,x,2]-fpb)<err:
queue.append([y+1, x])
visited[y+1, x] = 1
misc.imsave(f_out, image_out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment