简体   繁体   中英

thresholding in 3 color : black, white, and gray , instead of just black and white

I expect can threshold in 3 color: black, white, and gray, instead of just black and white, that later on I can separate the sticker out from original img

now my .py script can thresholding, make image's color to black and white color

import numpy as np
import glob
import matplotlib.pyplot as plt
import skimage.io
import skimage.color
import skimage.filters



# load the image
image = skimage.io.imread("/home/student_joy/desktop/optimization_11_10/original_duplicate.png")[:,:,:3]


# image = imageio.imread(image_name)[:,:,:3]
# img = rgb2gray(image)

fig, ax = plt.subplots()
plt.imshow(image)


# convert the image to grayscale
gray_image = skimage.color.rgb2gray(image)

# blur the image to denoise
blurred_image = skimage.filters.gaussian(gray_image, sigma=1.0)

fig, ax = plt.subplots()
plt.imshow(blurred_image, cmap="gray")

# create a histogram of the blurred grayscale image
histogram, bin_edges = np.histogram(blurred_image, bins=256, range=(0.0, 1.0))

fig, ax = plt.subplots()
plt.plot(bin_edges[0:-1], histogram)
plt.title("Grayscale Histogram")
plt.xlabel("grayscale value")
plt.ylabel("pixels")
plt.xlim(0, 1.0)

# create a mask based on the threshold
t = 0.72
binary_mask = blurred_image < t

fig, ax = plt.subplots()
plt.imshow(binary_mask, cmap="gray")


plt.show() 

see the result pic: https://imgur.com/a/u4KvF7Z

I'm not sure how to set properly binary_mask, the t value

binary_mask = blurred_image < t

As you are evaluating a boolean expression on the right, this will give either false (0) or true (1) as target values for your mask (which makes sense if you actually need a mask, it's a binary image).

If you want to separate the sticker regions only (so remove everything grey), you'd do something like

t1 = 0.5
t2 = 0.72
binary_mask = 1 - ((t1 < blurred_image) & (blurred_image < t2))

or use cv.threshold() for a similiar operation.

About finding you threshold: If you follow this link How to get threshold value from histogram? and look up the "Otsu's Binarization " section, it explains how to get a thresholding for a region with a bimodal histogram. Mask out the gray region you just found to only leave the black and white of the stickers, then let Otsu handle the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM