0

I want to separate my image's channels. Then, I want to apply Otsu Thresholding to each one, and finally, merge them together. However, in line 4 of my code, it gives me the following error:

File "C:/Users/Berke/PycharmProjects/goruntu/main.py", line 28, in <module>
    image_channels = np.split(np.asarray(gradient_image), 3, axis=2)
File "C:\Users\Berke\PycharmProjects\goruntu\venv\lib\site-packages\numpy\lib\shape_base.py", line 846, in split
    N = ary.shape[axis]
IndexError: tuple index out of range

Here's my code:

morph = mypic.copy()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 1))
myImage = cv2.morphologyEx(morph, cv2.MORPH_GRADIENT, kernel)
myImageChannels = np.split(np.asarray(gradient_image), 3, axis=2)
for channels in range(3):
  _, myImageChannels[channels] = cv2.threshold(myImageChannels[channels],
                                               0,
                                               255,
                                               cv2.THRESH_OTSU | cv2.THRESH_BINARY)
JamCon
  • 2,313
  • 2
  • 25
  • 34

1 Answers1

2

Why not easier way?

import numpy as np
import cv2

original_image = cv2.imread(path) #expect [X,Y,3] shape
#or
original_image = np.asarray(gradient_image)

otsu_image = np.zeros(shape=original_image.shape)
for channel in range(3):
    _,otsu_image[:,:,channel]= cv2.threshold(original_image[:,:channel],0,255,cv2.THRESH_OTSU | cv2.THRESH_BINARY)

By this [:,:,channel] index selection, you basicly access image layer of particular channel without doing anything special with the image. You can ofcourse assign thresholded image to that layer, because 1 channel layer has the same dimension as grayscale image

Martin
  • 3,333
  • 2
  • 18
  • 39
  • Got it, instead of split function. I can use [; , ; , index] notation. Thank you. – Türker Berke Yıldırım Mar 02 '19 at 16:12
  • @TürkerBerkeYıldırım I noticed you dont 'accept' any answers to questions you post on Stackoverflow. If someone answers your question and you are satisfied, this site works, that questioner accepts the answer for further references – Martin Mar 02 '19 at 16:21
  • I satisfied and give +1 for it. How can I "accept" an answer? – Türker Berke Yıldırım Mar 02 '19 at 16:51
  • @TürkerBerkeYıldırım Thanks, but what you did is 'Upvote', you need to select 'Check' symbol which is just under the number of votes. Maybe it would be good, when you have time, to accept your other questions, but of course only if they have answer that satisfied you :) – Martin Mar 02 '19 at 17:30
  • Oh, I see. I was thinking about that, the moderator gives Check button for correct answers :( – Türker Berke Yıldırım Mar 02 '19 at 18:51