import skimage
from skimage import io
import matplotlib.pyplot as plt
from skimage import data
from skimage.color import rgb2hsv, hsv2rgb
from skimage.segmentation import flood, flood_fill
You can see that this image is an aerial photograph that contains a yellow polygon outlining a section of the image.
alpha_image = io.imread('1.png')
image = alpha_image[:,:,:3]
plt.imshow(image)
After we detect the outline, we can show it in our notebook as a "mask image."
hsv_img = rgb2hsv(image)
hsv_img[:,:,2] = hsv_img[:,:,0] > 0.16
hsv_img[:,:,1] = hsv_img[:,:,0] > 0.16
hsv_img[:,:,0] = hsv_img[:,:,0] > 0.16
mask_image = hsv2rgb(hsv_img)
plt.imshow(mask_image)
def getNeighbours(i, j, n, m) :
arr = []
if i-1 >= 0 and j-1 >= 0 :
arr.append((i-1, j-1))
if i-1 >= 0 :
arr.append((i-1, j))
if i-1 >= 0 and j+1 < m :
arr.append((i-1, j+1))
if j+1 < m :
arr.append((i, j+1))
if i+1 < n and j+1 < m :
arr.append((i+1, j+1))
if i+1 < n :
arr.append((i+1, j))
if i+1 < n and j-1 >= 0 :
arr.append((i+1, j-1))
if j-1 >= 0 :
arr.append((i, j-1))
return arr
n = image.shape[0]
m = image.shape[1]
queue = [(0, 0)]
while len(queue) > 0:
p = queue.pop()
if mask_image[p[0], p[1], 0] == 0 :
arr = getNeighbours(p[0], p[1], n, m)
for a in arr:
queue.append(a)
mask_image[p[0], p[1], 0] = mask_image[p[0], p[1], 0] = mask_image[p[0], p[1], 0] = 1.0
plt.imshow(mask_image)
left = image.shape[1]
right = 0
top = image.shape[0]
bottom = 0
for i in range(n):
for j in range(m):
if mask_image[i, j, 0] != 1.0:
if i < top: top = i
if i > bottom: bottom = i
if j < left: left = j
if j > right: right = j
alpha_image = alpha_image[top:bottom+1, left:right+1, :]
mask_image = mask_image[top:bottom+1, left:right+1, :]
plt.imshow(alpha_image)
pixel_count = 0
for i in range(alpha_image.shape[0]):
for j in range(alpha_image.shape[1]):
if mask_image[i, j, 0] == 1.0:
alpha_image[i, j, 3] = 0.0
else:
pixel_count += 1
plt.imshow(alpha_image)
io.imsave("result.png", alpha_image)
original_size = image.shape[0] * image.shape[1]
print ("Image size: {} pixels".format(pixel_count))
if False:
print(pixel_count)
print(original_size)
n = image.shape[0]
m = image.shape[1]
print('mandn')
print(n)
print(m)
print('topandbottom')
print(top)
print(bottom)
print(left)
print(right)
print ("Image promience: {0:.2f}% of original document image".format(pixel_count / original_size * 100))