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
img = cv2.imread('filename.jpg')
# 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[0])
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)
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?