0

I need to threshold my image without using OpenCV function.

I know this way only, but in this case I am using cv2.threshold function from OpenCV:

img = cv2.imread('filename', 0)

_, thresh = cv2.threshold(img,127,255,cv.THRESH_BINARY)

How can I code thresholding without using cv2.threshold function.

I tried this one:

def thresholdimg(img, n):
    img_shape = img.shape
    height = img_shape[0]
    width = img_shape[1]
    for row in range(width):
        for column in range(height):
            if img[column, row] > s:
                img[column, row] = 0
            else:
                img[column, row] = 255
    return 

Where, n is equal to 127

Thanks in advance.

3
  • As StackOverflow isn’t a code-writing service, you should edit your honest attempt at coding this into your question. Commented Oct 11, 2020 at 21:43
  • This attempt is not for any service, I am a beginner in this field and I am trying to learn something. I wrote here just because I need a help. Commented Oct 11, 2020 at 21:47
  • It looks like you are still planning to use OpenCV to read/create the image. So why not also use OpenCV for thresholding? But if you want to use only lower-level libraries, you may be able to get there with a combination of Pillow and NumPy. See these for some ideas: note.nkmk.me/en/python-numpy-image-processing and note.nkmk.me/en/python-numpy-opencv-image-binarization Commented Oct 11, 2020 at 22:04

2 Answers 2

3

You can use numpy to threshold in Python without OpenCV.

image[image>127] = 255
image[image!=255] = 0

if image is a grayscale image.

Sign up to request clarification or add additional context in comments.

Comments

0

You can threshold like this:

thresholdIMG = image[:, :, <color channel>] > <threshold>

But if you are going to do that with a RGB image you will get weird results.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.