Search code examples
pythonnumpyopencvpixelmask

Replace pixel color by size as a condition in an image


I have this image: enter image description here

It's a meat peace, and I would like to measure the marble (white part). To do this I used this:

import numpy as np
import cv2

cv2.namedWindow('Image2', cv2.WINDOW_NORMAL)        # Create window with freedom of dimensions
cv2.resizeWindow('Image2', 600, 600)

def increase_brightness(img, value=30):
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)

    lim = 255 - value
    v[v > lim] = 0
    v[v <= lim] += value

    final_hsv = cv2.merge((h, s, v))
    return final_hsv

image = cv2.imread('image.jpeg')

image2 = increase_brightness(image)

lower_range=np.array([0, 155, 0])
upper_range=np.array([255,255,255])
mask=cv2.inRange(mask, lower_range, upper_range)

and I obtained this image:

enter image description here

but there is a noise in the final image. Is there a way to replace the black smallest pixels by white pixels, using, for example, the pixel size as a condition?

OR Is there a better approach to do this?


Solution

  • Here is one way using Python/OpenCV by using cv2.inRange() to threshold on white.

    Input:

    enter image description here

    import cv2
    import numpy as np
    
    # load image
    img = cv2.imread("meat.jpg")
    
    # threshold on white
    lower = (120,140,190)
    upper = (255,255,255)
    
    # create the mask and use it to change the colors
    thresh = cv2.inRange(img, lower, upper)
    
    # apply morphology to clean up small spots
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
    
    # count number of non-zero pixels
    count = np.count_nonzero(thresh)
    
    print("total white pixels =", count)
    
    # write thresh to disk
    cv2.imwrite("meat_thresh.png", thresh)
    
    # display it
    cv2.imshow("thresh", thresh)
    cv2.waitKey(0)
    

    enter image description here

    Textual Information:

    total white pixels = 41969