4

I have this image

enter image description here

When I apply

from skimage import filters
result_sobel = filters.sobel(image)

The image is

enter image description here

How can I remove the bounding box outline so it blends with the background?

Ideally, the output will be the black background, and the red in between without the outlined bounding box.

PolarBear10
  • 2,065
  • 7
  • 24
  • 55

2 Answers2

4

Here is one way in Python/OpenCV. Just get the contours from the original gray image. Then draw those in black over your red outline image as 3 pixels thick (Sobel edge thickness). I note that your two images are not the same size and the outlines are shifted relative to the gray boxes. Why is that?

Gray Original:

enter image description here

Sobel Red Edges:

enter image description here

import cv2
import numpy as np

# read original image as grayscale 
img = cv2.imread('gray_rectangle.png', cv2.IMREAD_GRAYSCALE)
hi, wi = img.shape[:2]

# read edge image
edges = cv2.imread('red_edges.png')

# edges image is larger than original and shifted, so crop it to same size
edges2 = edges[3:hi+3, 3:wi+3]

# threshold img
thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)[1]

# get contours and draw them as black on edges image
result = edges2.copy()
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
cv2.drawContours(result, contours, -1, (0,0,0), 3)

# write result to disk
cv2.imwrite("red_edges_removed.png", result)

# display it
cv2.imshow("ORIG", img)
cv2.imshow("EDGES", edges)
cv2.imshow("THRESH", thresh)
cv2.imshow("RESULT", result)
cv2.waitKey(0)


Result:

enter image description here

fmw42
  • 46,825
  • 10
  • 62
  • 80
  • This method is smart and impressive. Thank you very much. To answer your question about the shift in the image that is because I took a screenshot of the image instead of uploading it directly. I apologize for my incompetence. – PolarBear10 Mar 04 '20 at 21:32
  • Understood. Thanks for explaining the offset and size differences. – fmw42 Mar 05 '20 at 00:07
4

You can use a mask in skimage.filters.sobel:

import skimage

img = skimage.io.imread('N35nj.png', as_gray=True)   
mask = img > skimage.filters.threshold_otsu(img)
edges = skimage.filters.sobel(img, mask=mask)

Let's plot the result:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10,5))
ax[0].imshow(img, cmap='gray')
ax[0].set_title('Original image')

ax[1].imshow(edges, cmap='magma')
ax[1].set_title('Sobel edges')

for a in ax.ravel():
    a.axis('off')

plt.tight_layout()
plt.show()

enter image description here

Andreas K.
  • 9,282
  • 3
  • 40
  • 45