0
$\begingroup$

I am trying to get the following image to a certain grayscale value enter image description here

I want the spiral to have a grayscale of 120 and everything else to have a grayscale value of 255. What can I do?

$\endgroup$

1 Answer 1

2
$\begingroup$

For this specific task and if you don't care about how the method can be extended to other cases, the following python code does the job:

import numpy as np
import matplotlib.pyplot as plt
import sys

if __name__ == "__main__":
    img = plt.imread(sys.argv[1])

    img = img.astype(int)       # type conversion from uint8 to int
    # given that the spiral structure mostly consists of pixel with 0 value
    img += 120
    img = np.clip(img, 0, 255).astype(np.uint8)      # clip to valid image range and convert the int type img back to uint8
    plt.imsave("grayscale-120.jpg", img)

Note that, the original image does not just contain pixel value of 255 and 0, there are intermediate values. The code above does not get rid of the intermediate values (though, it is negligible). But if you really want to get rid of them, you can use:

img[img > 120] = 255

as a thresholded pixel value substitution before saving the image. This will yield images will exactly two pixel values (120 and 255). But... your image is of jpeg format, so you will notice some compression artifacts and the noise that hardly noticable before is enhanced by hard thresholding. Yet, you can use opening operation to get rid of the artifacts, right before you save the image:

import cv2
kernel = np.ones((3, 3),np.uint8)
img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)

well... this is not perfect, but I am sure more tweaking can be done here.

no hard thresholding hard thresholding with opening op
enter image description here enter image description here enter image description here
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.