简体   繁体   中英

Convert an image array to a binarized image

I have an Image array Indice which is like this:

array([[158,   0, 252, ..., 185, 186, 187],
   [254, 253, 252, ..., 188, 188, 189],
   [247, 249, 252, ..., 188, 187, 186],
   ..., 
   [176, 172, 168, ..., 204, 205, 205],
   [178, 175, 172, ..., 206, 205, 206],
   [180, 177, 174, ..., 206, 207, 207]], dtype=uint8)

I want to convert Indice to a binarized image (values between 0 and 1) with a threshehold near 0 (0.1 or 0.2). how can I do it in Python ?

You can use np.where to binarize the data after converting it to the range from 0 to 1 by dividing by 255

threshold = 0.2
new_indice = np.where(Indice/255>=threshold, 1, 0)

If a boolean binary array is fine for you, you can simply use numpy's element-wise comparison:

new_indice = (Indice/255 > threshold)

In fact, for random test arrays this seemed to be slightly faster than the np.where solution. In case you need an integer binary array you can simply add a 1* in front of the parentheses, but then the speed advantage seems to be gone.

An easy way to do this kind of task is by using list comprehensions .

In your case:

array([[1 if x>threshold else 0 for x in line] for line in Indice])

Where threshold would be set to the value you want.

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