How do i remove the background from this image, just want the lettuce from the picture?












0















image of lettuce



Just want to retain the lettuce, I have hundreds of image like this and would be comparing the size of lettuce, so to began with I tried the canny edge detection but it doesn't seems to work, any idea how shall move ahead with this










share|improve this question























  • can you post more sample images, like 5, just purely from this image, i think you can isolate the lettuce based on some custom intensity thresholding from the rgb channels.

    – teng
    Nov 23 '18 at 21:37











  • @teng all images are nearly same just the size of the leafs will increase, that too very minor increase in size. here's the google drive link you can have a look on sample images, drive.google.com/open?id=1HcaxCCKHEYSe4geIj5PjUiH6nf_AHsZZ

    – Anurag Chaudhary
    Nov 23 '18 at 21:46








  • 1





    Why do you think that a edge detecting algorythm would be any good at removing the lettuce from all those balls? there are so many edges in your image - that does not seem like a good idea. ... USe color thresholding - your lettuce is green the rest - rather not. the blue has probably some green in it - but marginally less then the lettuce...

    – Patrick Artner
    Nov 23 '18 at 21:47








  • 3





    Beside that .... SO is about fixing your Code - not implementing your ideas. Please go over how to ask and on-topic again and if you have questions provide your code as Minimal, Complete, and Verifiable example. Show what you tried and what did not work and we might be able to help you improve it - but dont use an edge detector for a color thresholding task ....

    – Patrick Artner
    Nov 23 '18 at 21:48













  • I would probably go with @PatrickArtner's approach, perhaps this is a good place to start: docs.opencv.org/3.4/da/d97/tutorial_threshold_inRange.html

    – andersource
    Nov 23 '18 at 22:19


















0















image of lettuce



Just want to retain the lettuce, I have hundreds of image like this and would be comparing the size of lettuce, so to began with I tried the canny edge detection but it doesn't seems to work, any idea how shall move ahead with this










share|improve this question























  • can you post more sample images, like 5, just purely from this image, i think you can isolate the lettuce based on some custom intensity thresholding from the rgb channels.

    – teng
    Nov 23 '18 at 21:37











  • @teng all images are nearly same just the size of the leafs will increase, that too very minor increase in size. here's the google drive link you can have a look on sample images, drive.google.com/open?id=1HcaxCCKHEYSe4geIj5PjUiH6nf_AHsZZ

    – Anurag Chaudhary
    Nov 23 '18 at 21:46








  • 1





    Why do you think that a edge detecting algorythm would be any good at removing the lettuce from all those balls? there are so many edges in your image - that does not seem like a good idea. ... USe color thresholding - your lettuce is green the rest - rather not. the blue has probably some green in it - but marginally less then the lettuce...

    – Patrick Artner
    Nov 23 '18 at 21:47








  • 3





    Beside that .... SO is about fixing your Code - not implementing your ideas. Please go over how to ask and on-topic again and if you have questions provide your code as Minimal, Complete, and Verifiable example. Show what you tried and what did not work and we might be able to help you improve it - but dont use an edge detector for a color thresholding task ....

    – Patrick Artner
    Nov 23 '18 at 21:48













  • I would probably go with @PatrickArtner's approach, perhaps this is a good place to start: docs.opencv.org/3.4/da/d97/tutorial_threshold_inRange.html

    – andersource
    Nov 23 '18 at 22:19
















0












0








0








image of lettuce



Just want to retain the lettuce, I have hundreds of image like this and would be comparing the size of lettuce, so to began with I tried the canny edge detection but it doesn't seems to work, any idea how shall move ahead with this










share|improve this question














image of lettuce



Just want to retain the lettuce, I have hundreds of image like this and would be comparing the size of lettuce, so to began with I tried the canny edge detection but it doesn't seems to work, any idea how shall move ahead with this







python opencv image-processing scikit-image edge-detection






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 21:32









Anurag ChaudharyAnurag Chaudhary

176




176













  • can you post more sample images, like 5, just purely from this image, i think you can isolate the lettuce based on some custom intensity thresholding from the rgb channels.

    – teng
    Nov 23 '18 at 21:37











  • @teng all images are nearly same just the size of the leafs will increase, that too very minor increase in size. here's the google drive link you can have a look on sample images, drive.google.com/open?id=1HcaxCCKHEYSe4geIj5PjUiH6nf_AHsZZ

    – Anurag Chaudhary
    Nov 23 '18 at 21:46








  • 1





    Why do you think that a edge detecting algorythm would be any good at removing the lettuce from all those balls? there are so many edges in your image - that does not seem like a good idea. ... USe color thresholding - your lettuce is green the rest - rather not. the blue has probably some green in it - but marginally less then the lettuce...

    – Patrick Artner
    Nov 23 '18 at 21:47








  • 3





    Beside that .... SO is about fixing your Code - not implementing your ideas. Please go over how to ask and on-topic again and if you have questions provide your code as Minimal, Complete, and Verifiable example. Show what you tried and what did not work and we might be able to help you improve it - but dont use an edge detector for a color thresholding task ....

    – Patrick Artner
    Nov 23 '18 at 21:48













  • I would probably go with @PatrickArtner's approach, perhaps this is a good place to start: docs.opencv.org/3.4/da/d97/tutorial_threshold_inRange.html

    – andersource
    Nov 23 '18 at 22:19





















  • can you post more sample images, like 5, just purely from this image, i think you can isolate the lettuce based on some custom intensity thresholding from the rgb channels.

    – teng
    Nov 23 '18 at 21:37











  • @teng all images are nearly same just the size of the leafs will increase, that too very minor increase in size. here's the google drive link you can have a look on sample images, drive.google.com/open?id=1HcaxCCKHEYSe4geIj5PjUiH6nf_AHsZZ

    – Anurag Chaudhary
    Nov 23 '18 at 21:46








  • 1





    Why do you think that a edge detecting algorythm would be any good at removing the lettuce from all those balls? there are so many edges in your image - that does not seem like a good idea. ... USe color thresholding - your lettuce is green the rest - rather not. the blue has probably some green in it - but marginally less then the lettuce...

    – Patrick Artner
    Nov 23 '18 at 21:47








  • 3





    Beside that .... SO is about fixing your Code - not implementing your ideas. Please go over how to ask and on-topic again and if you have questions provide your code as Minimal, Complete, and Verifiable example. Show what you tried and what did not work and we might be able to help you improve it - but dont use an edge detector for a color thresholding task ....

    – Patrick Artner
    Nov 23 '18 at 21:48













  • I would probably go with @PatrickArtner's approach, perhaps this is a good place to start: docs.opencv.org/3.4/da/d97/tutorial_threshold_inRange.html

    – andersource
    Nov 23 '18 at 22:19



















can you post more sample images, like 5, just purely from this image, i think you can isolate the lettuce based on some custom intensity thresholding from the rgb channels.

– teng
Nov 23 '18 at 21:37





can you post more sample images, like 5, just purely from this image, i think you can isolate the lettuce based on some custom intensity thresholding from the rgb channels.

– teng
Nov 23 '18 at 21:37













@teng all images are nearly same just the size of the leafs will increase, that too very minor increase in size. here's the google drive link you can have a look on sample images, drive.google.com/open?id=1HcaxCCKHEYSe4geIj5PjUiH6nf_AHsZZ

– Anurag Chaudhary
Nov 23 '18 at 21:46







@teng all images are nearly same just the size of the leafs will increase, that too very minor increase in size. here's the google drive link you can have a look on sample images, drive.google.com/open?id=1HcaxCCKHEYSe4geIj5PjUiH6nf_AHsZZ

– Anurag Chaudhary
Nov 23 '18 at 21:46






1




1





Why do you think that a edge detecting algorythm would be any good at removing the lettuce from all those balls? there are so many edges in your image - that does not seem like a good idea. ... USe color thresholding - your lettuce is green the rest - rather not. the blue has probably some green in it - but marginally less then the lettuce...

– Patrick Artner
Nov 23 '18 at 21:47







Why do you think that a edge detecting algorythm would be any good at removing the lettuce from all those balls? there are so many edges in your image - that does not seem like a good idea. ... USe color thresholding - your lettuce is green the rest - rather not. the blue has probably some green in it - but marginally less then the lettuce...

– Patrick Artner
Nov 23 '18 at 21:47






3




3





Beside that .... SO is about fixing your Code - not implementing your ideas. Please go over how to ask and on-topic again and if you have questions provide your code as Minimal, Complete, and Verifiable example. Show what you tried and what did not work and we might be able to help you improve it - but dont use an edge detector for a color thresholding task ....

– Patrick Artner
Nov 23 '18 at 21:48







Beside that .... SO is about fixing your Code - not implementing your ideas. Please go over how to ask and on-topic again and if you have questions provide your code as Minimal, Complete, and Verifiable example. Show what you tried and what did not work and we might be able to help you improve it - but dont use an edge detector for a color thresholding task ....

– Patrick Artner
Nov 23 '18 at 21:48















I would probably go with @PatrickArtner's approach, perhaps this is a good place to start: docs.opencv.org/3.4/da/d97/tutorial_threshold_inRange.html

– andersource
Nov 23 '18 at 22:19







I would probably go with @PatrickArtner's approach, perhaps this is a good place to start: docs.opencv.org/3.4/da/d97/tutorial_threshold_inRange.html

– andersource
Nov 23 '18 at 22:19














3 Answers
3






active

oldest

votes


















0














You can convert the RGB image into HSV image and segment the Green color region.



import cv2
import numpy as np

frame=cv2.imread('a.png')
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

lower = np.array([50,50,50])
upper = np.array([70,255,255])

mask = cv2.inRange(hsv, lower, upper)
res = cv2.bitwise_and(frame,frame, mask= mask)

cv2.imshow('frame',frame)
cv2.imshow('res',res)
cv2.waitKey(0)
cv2.destroyAllWindows()


The final output






share|improve this answer































    1














    A possible approach is by using the Graph Segmentation method (cv::ximgproc::segmentation::GraphSegmentation), that you apply to the image converted to HSV or HSL, where you set the V or L plane to a constant to flatten illumination.






    share|improve this answer



















    • 1





      up voted for the illumination flattening suggestion.

      – teng
      Nov 23 '18 at 23:10



















    0














    You may get away with thresholding as long as you fix your lighting (method 1 listed below), if not, you might need a simple classifier method (for example a clustering technique, method 2) in conjunction with connected components and assumption on the location of the plant or color to assign the detected class to the plant.



    from scipy.misc import imread
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    %matplotlib inline
    import matplotlib
    import numpy as np

    # read the image
    img = imread('9v5wv.png')

    # show the image
    fig,ax = plt.subplots(1)
    ax.imshow(img)
    ax.grid('off')

    # show the r,g,b channels separately.
    for n,d in enumerate([('r',0),('g',1),('b',2)]):
    k,v = d
    plt.figure(n)
    plt.subplot(131)
    plt.imshow(arr[:,:,v],cmap='gray')
    plt.grid('off')
    plt.title(k)
    plt.subplot(133)
    _=plt.hist(arr[:,:,v].ravel(),bins=100)


    # method 1, rgb thresholding will not work when lighting changes
    arr = img

    r_filter = lambda x: x[:,:,0] < 100
    g_filter = lambda x: x[:,:,1] > 80
    b_filter = lambda x: x[:,:,2] < 200
    mask=np.logical_and(np.logical_and(r_filter(arr),g_filter(arr)),b_filter(arr))


    plt.imshow(mask,cmap='gray')
    plt.grid('off')


    enter image description here



    # method 2, kmeans clustering
    from sklearn.cluster import KMeans
    arr = matplotlib.colors.rgb_to_hsv(img[:,:,0:3])
    # ignore v per Yves Daoust
    data = np.array(arr[:,:,0:2])
    x,y,z = data.shape
    X = np.reshape(data,(x*y,z))
    kmeans = KMeans(n_clusters=6, random_state=420).fit(X)
    mask = np.reshape(kmeans.labels_,(x,y,))

    plt.imshow(mask==0,cmap='gray')
    plt.grid('off')


    enter image description here






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53453157%2fhow-do-i-remove-the-background-from-this-image-just-want-the-lettuce-from-the-p%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      You can convert the RGB image into HSV image and segment the Green color region.



      import cv2
      import numpy as np

      frame=cv2.imread('a.png')
      hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

      lower = np.array([50,50,50])
      upper = np.array([70,255,255])

      mask = cv2.inRange(hsv, lower, upper)
      res = cv2.bitwise_and(frame,frame, mask= mask)

      cv2.imshow('frame',frame)
      cv2.imshow('res',res)
      cv2.waitKey(0)
      cv2.destroyAllWindows()


      The final output






      share|improve this answer




























        0














        You can convert the RGB image into HSV image and segment the Green color region.



        import cv2
        import numpy as np

        frame=cv2.imread('a.png')
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

        lower = np.array([50,50,50])
        upper = np.array([70,255,255])

        mask = cv2.inRange(hsv, lower, upper)
        res = cv2.bitwise_and(frame,frame, mask= mask)

        cv2.imshow('frame',frame)
        cv2.imshow('res',res)
        cv2.waitKey(0)
        cv2.destroyAllWindows()


        The final output






        share|improve this answer


























          0












          0








          0







          You can convert the RGB image into HSV image and segment the Green color region.



          import cv2
          import numpy as np

          frame=cv2.imread('a.png')
          hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

          lower = np.array([50,50,50])
          upper = np.array([70,255,255])

          mask = cv2.inRange(hsv, lower, upper)
          res = cv2.bitwise_and(frame,frame, mask= mask)

          cv2.imshow('frame',frame)
          cv2.imshow('res',res)
          cv2.waitKey(0)
          cv2.destroyAllWindows()


          The final output






          share|improve this answer













          You can convert the RGB image into HSV image and segment the Green color region.



          import cv2
          import numpy as np

          frame=cv2.imread('a.png')
          hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

          lower = np.array([50,50,50])
          upper = np.array([70,255,255])

          mask = cv2.inRange(hsv, lower, upper)
          res = cv2.bitwise_and(frame,frame, mask= mask)

          cv2.imshow('frame',frame)
          cv2.imshow('res',res)
          cv2.waitKey(0)
          cv2.destroyAllWindows()


          The final output







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 24 '18 at 0:18









          Joy MazumderJoy Mazumder

          58116




          58116

























              1














              A possible approach is by using the Graph Segmentation method (cv::ximgproc::segmentation::GraphSegmentation), that you apply to the image converted to HSV or HSL, where you set the V or L plane to a constant to flatten illumination.






              share|improve this answer



















              • 1





                up voted for the illumination flattening suggestion.

                – teng
                Nov 23 '18 at 23:10
















              1














              A possible approach is by using the Graph Segmentation method (cv::ximgproc::segmentation::GraphSegmentation), that you apply to the image converted to HSV or HSL, where you set the V or L plane to a constant to flatten illumination.






              share|improve this answer



















              • 1





                up voted for the illumination flattening suggestion.

                – teng
                Nov 23 '18 at 23:10














              1












              1








              1







              A possible approach is by using the Graph Segmentation method (cv::ximgproc::segmentation::GraphSegmentation), that you apply to the image converted to HSV or HSL, where you set the V or L plane to a constant to flatten illumination.






              share|improve this answer













              A possible approach is by using the Graph Segmentation method (cv::ximgproc::segmentation::GraphSegmentation), that you apply to the image converted to HSV or HSL, where you set the V or L plane to a constant to flatten illumination.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 23 '18 at 22:35









              Yves DaoustYves Daoust

              37.7k72659




              37.7k72659








              • 1





                up voted for the illumination flattening suggestion.

                – teng
                Nov 23 '18 at 23:10














              • 1





                up voted for the illumination flattening suggestion.

                – teng
                Nov 23 '18 at 23:10








              1




              1





              up voted for the illumination flattening suggestion.

              – teng
              Nov 23 '18 at 23:10





              up voted for the illumination flattening suggestion.

              – teng
              Nov 23 '18 at 23:10











              0














              You may get away with thresholding as long as you fix your lighting (method 1 listed below), if not, you might need a simple classifier method (for example a clustering technique, method 2) in conjunction with connected components and assumption on the location of the plant or color to assign the detected class to the plant.



              from scipy.misc import imread
              import matplotlib.pyplot as plt
              import matplotlib.patches as patches
              %matplotlib inline
              import matplotlib
              import numpy as np

              # read the image
              img = imread('9v5wv.png')

              # show the image
              fig,ax = plt.subplots(1)
              ax.imshow(img)
              ax.grid('off')

              # show the r,g,b channels separately.
              for n,d in enumerate([('r',0),('g',1),('b',2)]):
              k,v = d
              plt.figure(n)
              plt.subplot(131)
              plt.imshow(arr[:,:,v],cmap='gray')
              plt.grid('off')
              plt.title(k)
              plt.subplot(133)
              _=plt.hist(arr[:,:,v].ravel(),bins=100)


              # method 1, rgb thresholding will not work when lighting changes
              arr = img

              r_filter = lambda x: x[:,:,0] < 100
              g_filter = lambda x: x[:,:,1] > 80
              b_filter = lambda x: x[:,:,2] < 200
              mask=np.logical_and(np.logical_and(r_filter(arr),g_filter(arr)),b_filter(arr))


              plt.imshow(mask,cmap='gray')
              plt.grid('off')


              enter image description here



              # method 2, kmeans clustering
              from sklearn.cluster import KMeans
              arr = matplotlib.colors.rgb_to_hsv(img[:,:,0:3])
              # ignore v per Yves Daoust
              data = np.array(arr[:,:,0:2])
              x,y,z = data.shape
              X = np.reshape(data,(x*y,z))
              kmeans = KMeans(n_clusters=6, random_state=420).fit(X)
              mask = np.reshape(kmeans.labels_,(x,y,))

              plt.imshow(mask==0,cmap='gray')
              plt.grid('off')


              enter image description here






              share|improve this answer




























                0














                You may get away with thresholding as long as you fix your lighting (method 1 listed below), if not, you might need a simple classifier method (for example a clustering technique, method 2) in conjunction with connected components and assumption on the location of the plant or color to assign the detected class to the plant.



                from scipy.misc import imread
                import matplotlib.pyplot as plt
                import matplotlib.patches as patches
                %matplotlib inline
                import matplotlib
                import numpy as np

                # read the image
                img = imread('9v5wv.png')

                # show the image
                fig,ax = plt.subplots(1)
                ax.imshow(img)
                ax.grid('off')

                # show the r,g,b channels separately.
                for n,d in enumerate([('r',0),('g',1),('b',2)]):
                k,v = d
                plt.figure(n)
                plt.subplot(131)
                plt.imshow(arr[:,:,v],cmap='gray')
                plt.grid('off')
                plt.title(k)
                plt.subplot(133)
                _=plt.hist(arr[:,:,v].ravel(),bins=100)


                # method 1, rgb thresholding will not work when lighting changes
                arr = img

                r_filter = lambda x: x[:,:,0] < 100
                g_filter = lambda x: x[:,:,1] > 80
                b_filter = lambda x: x[:,:,2] < 200
                mask=np.logical_and(np.logical_and(r_filter(arr),g_filter(arr)),b_filter(arr))


                plt.imshow(mask,cmap='gray')
                plt.grid('off')


                enter image description here



                # method 2, kmeans clustering
                from sklearn.cluster import KMeans
                arr = matplotlib.colors.rgb_to_hsv(img[:,:,0:3])
                # ignore v per Yves Daoust
                data = np.array(arr[:,:,0:2])
                x,y,z = data.shape
                X = np.reshape(data,(x*y,z))
                kmeans = KMeans(n_clusters=6, random_state=420).fit(X)
                mask = np.reshape(kmeans.labels_,(x,y,))

                plt.imshow(mask==0,cmap='gray')
                plt.grid('off')


                enter image description here






                share|improve this answer


























                  0












                  0








                  0







                  You may get away with thresholding as long as you fix your lighting (method 1 listed below), if not, you might need a simple classifier method (for example a clustering technique, method 2) in conjunction with connected components and assumption on the location of the plant or color to assign the detected class to the plant.



                  from scipy.misc import imread
                  import matplotlib.pyplot as plt
                  import matplotlib.patches as patches
                  %matplotlib inline
                  import matplotlib
                  import numpy as np

                  # read the image
                  img = imread('9v5wv.png')

                  # show the image
                  fig,ax = plt.subplots(1)
                  ax.imshow(img)
                  ax.grid('off')

                  # show the r,g,b channels separately.
                  for n,d in enumerate([('r',0),('g',1),('b',2)]):
                  k,v = d
                  plt.figure(n)
                  plt.subplot(131)
                  plt.imshow(arr[:,:,v],cmap='gray')
                  plt.grid('off')
                  plt.title(k)
                  plt.subplot(133)
                  _=plt.hist(arr[:,:,v].ravel(),bins=100)


                  # method 1, rgb thresholding will not work when lighting changes
                  arr = img

                  r_filter = lambda x: x[:,:,0] < 100
                  g_filter = lambda x: x[:,:,1] > 80
                  b_filter = lambda x: x[:,:,2] < 200
                  mask=np.logical_and(np.logical_and(r_filter(arr),g_filter(arr)),b_filter(arr))


                  plt.imshow(mask,cmap='gray')
                  plt.grid('off')


                  enter image description here



                  # method 2, kmeans clustering
                  from sklearn.cluster import KMeans
                  arr = matplotlib.colors.rgb_to_hsv(img[:,:,0:3])
                  # ignore v per Yves Daoust
                  data = np.array(arr[:,:,0:2])
                  x,y,z = data.shape
                  X = np.reshape(data,(x*y,z))
                  kmeans = KMeans(n_clusters=6, random_state=420).fit(X)
                  mask = np.reshape(kmeans.labels_,(x,y,))

                  plt.imshow(mask==0,cmap='gray')
                  plt.grid('off')


                  enter image description here






                  share|improve this answer













                  You may get away with thresholding as long as you fix your lighting (method 1 listed below), if not, you might need a simple classifier method (for example a clustering technique, method 2) in conjunction with connected components and assumption on the location of the plant or color to assign the detected class to the plant.



                  from scipy.misc import imread
                  import matplotlib.pyplot as plt
                  import matplotlib.patches as patches
                  %matplotlib inline
                  import matplotlib
                  import numpy as np

                  # read the image
                  img = imread('9v5wv.png')

                  # show the image
                  fig,ax = plt.subplots(1)
                  ax.imshow(img)
                  ax.grid('off')

                  # show the r,g,b channels separately.
                  for n,d in enumerate([('r',0),('g',1),('b',2)]):
                  k,v = d
                  plt.figure(n)
                  plt.subplot(131)
                  plt.imshow(arr[:,:,v],cmap='gray')
                  plt.grid('off')
                  plt.title(k)
                  plt.subplot(133)
                  _=plt.hist(arr[:,:,v].ravel(),bins=100)


                  # method 1, rgb thresholding will not work when lighting changes
                  arr = img

                  r_filter = lambda x: x[:,:,0] < 100
                  g_filter = lambda x: x[:,:,1] > 80
                  b_filter = lambda x: x[:,:,2] < 200
                  mask=np.logical_and(np.logical_and(r_filter(arr),g_filter(arr)),b_filter(arr))


                  plt.imshow(mask,cmap='gray')
                  plt.grid('off')


                  enter image description here



                  # method 2, kmeans clustering
                  from sklearn.cluster import KMeans
                  arr = matplotlib.colors.rgb_to_hsv(img[:,:,0:3])
                  # ignore v per Yves Daoust
                  data = np.array(arr[:,:,0:2])
                  x,y,z = data.shape
                  X = np.reshape(data,(x*y,z))
                  kmeans = KMeans(n_clusters=6, random_state=420).fit(X)
                  mask = np.reshape(kmeans.labels_,(x,y,))

                  plt.imshow(mask==0,cmap='gray')
                  plt.grid('off')


                  enter image description here







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '18 at 23:09









                  tengteng

                  840721




                  840721






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53453157%2fhow-do-i-remove-the-background-from-this-image-just-want-the-lettuce-from-the-p%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Costa Masnaga

                      Fotorealismo

                      Sidney Franklin