# Whiten black contours around a skewed image

I have this image: I want to whiten the black contours (borders) around it without affecting the image content. Here is the code I used:

import cv2
import numpy as np
import shapely.geometry as shageo

# get the gray image and do binaryzation
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray[gray < 20] = 0
gray[gray > 0] = 255

# get the largest boundry of the binary image to locate the target
contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours)
box = cv2.boxPoints(rect)
box = np.int0(box)

poly = shageo.Polygon(box)
h, w = img.shape[:2]
ind = np.zeros((h, w), np.bool)

# check if the point is inside the target or not
for i in range(h):
for j in range(w):
p = shageo.Point(j, i)
if not p.within(poly):
ind[i, j] = True

# whiten the outside points
img[ind] = (255, 255, 255)
cv2.imwrite('result.jpg', img)


Here is the result: The code works fine, but it's very slow because of the for loops.

Any suggestions how to avoid the for loops or to make them faster?

After some research, I ended to a better and faster solution. Here is the code:

# import packages
import numpy
import mahotas.polygon
import shapely.geometry as shageo
import cv2
import numpy as np

# create a numpy array of zeros with the same dimensions of the image
canvas = numpy.zeros((dims, dims), dtype=int)
# the points coords in the form of pt(y, x)

# fill the polygon with ones.
mahotas.polygon.fill_polygon(pts, canvas)
return canvas

def find_polygon(img):
# get the gray image and do binaryzation
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray[gray < 20] = 0
gray[gray > 0] = 255

# get the largest boundry of the binary image to locate the target
contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours)
box = cv2.boxPoints(rect)
box = np.int0(box)
poly = shageo.Polygon(box)
# return the polygone coords in a list
return list(poly.exterior.coords)

def main():
# get the coords of the polygon containing (around) the image.
coords = find_polygon(img)
poly_coords = []
# the coords are floats and sometimes are negaive (-1), so transform them into positive ints.
for element in coords:
poly_coords.append(tuple(map(int, map(abs, reversed(element)))))

# convert the mask into array of 0 and 1. 