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.

Miki
  • 40,887
  • 13
  • 123
  • 202
rauffatali
  • 43
  • 1
  • 6
  • As StackOverflow isn’t a code-writing service, you should edit your honest attempt at coding this into your question. – DisappointedByUnaccountableMod Oct 11 '20 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. – rauffatali Oct 11 '20 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: https://note.nkmk.me/en/python-numpy-image-processing/ and https://note.nkmk.me/en/python-numpy-opencv-image-binarization/ – Matthias Fripp Oct 11 '20 at 22:04

2 Answers2

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.

fmw42
  • 46,825
  • 10
  • 62
  • 80
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.

Sanlyn
  • 139
  • 1
  • 12