简体   繁体   中英

Thresholding image using opencv library in python with different flags using for loop

I imported cv2 as cv, created a list of threshold flags, concatenated 'cv.' with the flags and then created a for loop for passing the flags as arguments. But python shows TypeError. I have attached the image of the output. Kindly help me create all the possible thresholds using a loop or some other way except for explicitly mentioning the flags every time.

[ 代码的输出 - Jupyter ]

In OpenCV, the given threshold options (eg cv.THRESH_BINARY or cv.THRESH_BINARY_INV) are actually constant integer values. You are trying to use strings instead of these integer values. That is the reason why you get the Type Error. If you want to apply all these different thresholds in a loop, one option is to create a different list for these options, like this:

threshold_options = [cv.THRESH_BINARY, cv.THRESH_BINARY_INV, ...]

That way, you can then use the values of this list in the loop as follows:

retval, thresh = cv.threshold(img, 127, 255, threshold_options[i])

The entire code would be as follows:

titles = [ 'THRESH_BINARY',
'THRESH_BINARY_INV',
'THRESH_MASK',
'THRESH_OTSU',
'THRESH_TOZERO',
'THRESH_TOZERO_INV',
'THRESH_TRIANGLE',
'THRESH_TRUNC']

threshold_options = [ cv.THRESH_BINARY,
cv.THRESH_BINARY_INV,
cv.THRESH_MASK,
cv.THRESH_OTSU,
cv.THRESH_TOZERO,
cv.THRESH_TOZERO_INV,
cv.THRESH_TRIANGLE,
cv.THRESH_TRUNC]


for i in range(len(titles)):
    retval, thresh = cv.threshold(img, 127, 255, threshold_options[i])
    plt.subplot(2,3,i+1), plt.title(titles[i]), plt.imshow(thresh, 'gray')
plt.show()

This might be related: OpenCV Thresholding example

First off, there is no need to use range , you can simply do for flag in titles: and pass flag . Have you checked if your image is loaded correctly? Are you sure that your flag is repsonsible for your error?

For future posts, please include a minimal reproducible example.

You code is not working because the type of the flags is int and not string .

You can print the type: print(type(cv.THRESH_BINARY)) .
The result is <class 'int'> .

You may create a list of int s:

th_flags = [cv.THRESH_BINARY, cv.THRESH_BINARY_INV, cv.THRESH_TRUNC, cv.THRESH_TOZERO, cv.THRESH_TOZERO_INV]

for th in th_flags:
    retval, thresh = cv.threshold(img, 127, 255, th)
    cv.imshow('thresh', thresh)
    cv.waitKey(1000)

cv.destroyAllWindows()

The code doesn't cover all the possible options .
Few flags can be combined using summation.

Example:

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

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