smoothing or deleting white background in an image with python-opencv

113 views Asked by At

i'm pretty new to OpenCV and i have to do some work for it for uni. My issue is to make the Background perfectly white (who is already white but has some stains). for this i used this code:

This is the original image I used:

enter image description here

The result I got is just the boundingbox of my object drawn in black this is the result image:

enter image description here

This is the code I used:

 
import cv2
import numpy as np

image = cv2.imread('./MCP_tmp_picam_final.jpg')
original = image.copy()

gray = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.adaptiveThreshold(blur,225,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,21,2)

# Draw boundingboxes onto a mask
mask = np.zeros(original.shape[:2], dtype=np.uint8)
cnts,_ = cv2.findContours(thresh, cv2.RETR_TREE,
                                cv2.CHAIN_APPROX_SIMPLE)

for i, c in enumerate(cnts):
    area = cv2.contourArea(c)
    # Ignore contours that are too small or too large
    if area < 1000 or 100000 < area: #100000
        continue
    rect = cv2.minAreaRect(c)
    #print(rect)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(mask, [box], 0, (255,255,255), 2)
    cv2.drawContours(image,[box],0,(0,0,255),2)

# Bitwise-and for result
result = cv2.bitwise_and(original, original, mask=mask)
result[mask==0] = (255,255,255)

cv2.imshow('result', result)
cv2.imshow('mask', mask)
cv2.imshow('image', image)
cv2.waitKey()

The result should have the hole component with a completely white background. It would be great if someone can help me with it.

PS: I'm using the result Image in a matching algorithm but this should be next step.

1

There are 1 answers

1
357865 On

I might have misunderstood this question, but I think something like this might be what you want:

import numpy as np

image = cv2.imread('./MCP_tmp_picam_final.jpg')

mask = np.any(image > 100, axis=2)
image[mask] = 255

cv2.imshow('result', image)
cv2.waitKey()