Class made to do some basic RGB analysis

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
4
down vote

favorite
1












I created this class to load in an image and get some specific values I needed.



from PIL import Image
import pandas as pd

class Img:
def __init__(self,filename):
self.name = filename
self.image = Image.open(self.name) # open image using PIL

# convert the image to a pandas df
self.df = pd.DataFrame(data=list(self.image.getdata()))

# get the RGB values from the image
self.rList = self.df[0]
self.gList = self.df[1]
self.bList = self.df[2]

# get the mean RGB values from the image
def getMean(self,rgb):
return rgb.mean()

self.r = getMean(self,self.rList)
self.g = getMean(self,self.gList)
self.b = getMean(self,self.bList)

# calculate luminance(brightness) based on the RGB values
def lumi(self):
l = (0.299*self.rList + 0.587*self.gList + 0.114*self.bList)
return l[l!=0]

self.l = lumi(self)

# calculate the contrast using the Michelson contrast formula.
def con(self):
min = self.l.quantile(0.05)
max = self.l.quantile(0.95)
return ((max-min) / (max + min))

self.contrast = con(self)


My goal: With the class structure created, I intend to create some instances into an list and plot values.



def loadImages(folder):
images =
for image in os.listdir(folder+'/'):
if image.endswith('.jpg'):
name = folder+'/'+image
images.append(Img(name))
return images

images = loadImages('faces')

from matplotlib import pyplot as plt

plt.scatter([x for x in range(0,len(images))],[x.b for x in images])






share|improve this question





















  • This seems to be lacking context. What are these 'specific values' you talk of? Which 'instances' and what values?
    – Daniel
    Jun 7 at 19:35






  • 1




    And... What is the question?
    – Félix Gagnon-Grenier
    Jun 7 at 22:27
















up vote
4
down vote

favorite
1












I created this class to load in an image and get some specific values I needed.



from PIL import Image
import pandas as pd

class Img:
def __init__(self,filename):
self.name = filename
self.image = Image.open(self.name) # open image using PIL

# convert the image to a pandas df
self.df = pd.DataFrame(data=list(self.image.getdata()))

# get the RGB values from the image
self.rList = self.df[0]
self.gList = self.df[1]
self.bList = self.df[2]

# get the mean RGB values from the image
def getMean(self,rgb):
return rgb.mean()

self.r = getMean(self,self.rList)
self.g = getMean(self,self.gList)
self.b = getMean(self,self.bList)

# calculate luminance(brightness) based on the RGB values
def lumi(self):
l = (0.299*self.rList + 0.587*self.gList + 0.114*self.bList)
return l[l!=0]

self.l = lumi(self)

# calculate the contrast using the Michelson contrast formula.
def con(self):
min = self.l.quantile(0.05)
max = self.l.quantile(0.95)
return ((max-min) / (max + min))

self.contrast = con(self)


My goal: With the class structure created, I intend to create some instances into an list and plot values.



def loadImages(folder):
images =
for image in os.listdir(folder+'/'):
if image.endswith('.jpg'):
name = folder+'/'+image
images.append(Img(name))
return images

images = loadImages('faces')

from matplotlib import pyplot as plt

plt.scatter([x for x in range(0,len(images))],[x.b for x in images])






share|improve this question





















  • This seems to be lacking context. What are these 'specific values' you talk of? Which 'instances' and what values?
    – Daniel
    Jun 7 at 19:35






  • 1




    And... What is the question?
    – Félix Gagnon-Grenier
    Jun 7 at 22:27












up vote
4
down vote

favorite
1









up vote
4
down vote

favorite
1






1





I created this class to load in an image and get some specific values I needed.



from PIL import Image
import pandas as pd

class Img:
def __init__(self,filename):
self.name = filename
self.image = Image.open(self.name) # open image using PIL

# convert the image to a pandas df
self.df = pd.DataFrame(data=list(self.image.getdata()))

# get the RGB values from the image
self.rList = self.df[0]
self.gList = self.df[1]
self.bList = self.df[2]

# get the mean RGB values from the image
def getMean(self,rgb):
return rgb.mean()

self.r = getMean(self,self.rList)
self.g = getMean(self,self.gList)
self.b = getMean(self,self.bList)

# calculate luminance(brightness) based on the RGB values
def lumi(self):
l = (0.299*self.rList + 0.587*self.gList + 0.114*self.bList)
return l[l!=0]

self.l = lumi(self)

# calculate the contrast using the Michelson contrast formula.
def con(self):
min = self.l.quantile(0.05)
max = self.l.quantile(0.95)
return ((max-min) / (max + min))

self.contrast = con(self)


My goal: With the class structure created, I intend to create some instances into an list and plot values.



def loadImages(folder):
images =
for image in os.listdir(folder+'/'):
if image.endswith('.jpg'):
name = folder+'/'+image
images.append(Img(name))
return images

images = loadImages('faces')

from matplotlib import pyplot as plt

plt.scatter([x for x in range(0,len(images))],[x.b for x in images])






share|improve this question













I created this class to load in an image and get some specific values I needed.



from PIL import Image
import pandas as pd

class Img:
def __init__(self,filename):
self.name = filename
self.image = Image.open(self.name) # open image using PIL

# convert the image to a pandas df
self.df = pd.DataFrame(data=list(self.image.getdata()))

# get the RGB values from the image
self.rList = self.df[0]
self.gList = self.df[1]
self.bList = self.df[2]

# get the mean RGB values from the image
def getMean(self,rgb):
return rgb.mean()

self.r = getMean(self,self.rList)
self.g = getMean(self,self.gList)
self.b = getMean(self,self.bList)

# calculate luminance(brightness) based on the RGB values
def lumi(self):
l = (0.299*self.rList + 0.587*self.gList + 0.114*self.bList)
return l[l!=0]

self.l = lumi(self)

# calculate the contrast using the Michelson contrast formula.
def con(self):
min = self.l.quantile(0.05)
max = self.l.quantile(0.95)
return ((max-min) / (max + min))

self.contrast = con(self)


My goal: With the class structure created, I intend to create some instances into an list and plot values.



def loadImages(folder):
images =
for image in os.listdir(folder+'/'):
if image.endswith('.jpg'):
name = folder+'/'+image
images.append(Img(name))
return images

images = loadImages('faces')

from matplotlib import pyplot as plt

plt.scatter([x for x in range(0,len(images))],[x.b for x in images])








share|improve this question












share|improve this question




share|improve this question








edited Jun 7 at 14:28









200_success

123k14143399




123k14143399









asked Jun 7 at 10:20









Mitchell van Zuylen

1241




1241











  • This seems to be lacking context. What are these 'specific values' you talk of? Which 'instances' and what values?
    – Daniel
    Jun 7 at 19:35






  • 1




    And... What is the question?
    – Félix Gagnon-Grenier
    Jun 7 at 22:27
















  • This seems to be lacking context. What are these 'specific values' you talk of? Which 'instances' and what values?
    – Daniel
    Jun 7 at 19:35






  • 1




    And... What is the question?
    – Félix Gagnon-Grenier
    Jun 7 at 22:27















This seems to be lacking context. What are these 'specific values' you talk of? Which 'instances' and what values?
– Daniel
Jun 7 at 19:35




This seems to be lacking context. What are these 'specific values' you talk of? Which 'instances' and what values?
– Daniel
Jun 7 at 19:35




1




1




And... What is the question?
– Félix Gagnon-Grenier
Jun 7 at 22:27




And... What is the question?
– Félix Gagnon-Grenier
Jun 7 at 22:27










1 Answer
1






active

oldest

votes

















up vote
1
down vote













All those inner functions in your constructor are unnecessary. Inner functions should be used sparingly, normally you have only these cases:



  1. Functions which can do something based on parameters you pass to it and which are not directly related to some object. Make these functions stand-alone functions.

  2. Functions which do something with an object or return some information about that object. Make these functions methods (or properties) of the class of the object.

  3. Functions which logically belong to some class because they make only sense in combination with them. Make these functions static methods of the class (by adding the decorator @staticmethod).

In your case I would do Option 2 (with the addition of making them properties which will be calculated when you first access them).



class Img:
def __init__(self,filename):
self.name = filename
self.image = Image.open(self.name) # open image using PIL

# convert the image to a pandas df
self.df = pd.DataFrame(data=list(self.image.getdata()))

# get the RGB values from the image
self.r = self.df[0].mean()
self.g = self.df[1].mean()
self.b = self.df[2].mean()

self._luminance = None
self._contrast = None

@property
def luminance(self):
"""Calculate luminance (brightness) based on the RGB values"""
if self._luminance is None:
self._luminance = (0.299*self.r + 0.587*self.g + 0.114*self.b)
return self._luminance

@property
def contrast(self):
"""Calculate the contrast using the Michelson contrast formula."""
if self._contrast is None:
min_ = self.luminance.quantile(0.05)
max_ = self.luminance.quantile(0.95)
self._contrast = (max_ - min_) / (max_ + min_)
return self._contrast





share|improve this answer





















    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    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: "196"
    ;
    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',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196021%2fclass-made-to-do-some-basic-rgb-analysis%23new-answer', 'question_page');

    );

    Post as a guest






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote













    All those inner functions in your constructor are unnecessary. Inner functions should be used sparingly, normally you have only these cases:



    1. Functions which can do something based on parameters you pass to it and which are not directly related to some object. Make these functions stand-alone functions.

    2. Functions which do something with an object or return some information about that object. Make these functions methods (or properties) of the class of the object.

    3. Functions which logically belong to some class because they make only sense in combination with them. Make these functions static methods of the class (by adding the decorator @staticmethod).

    In your case I would do Option 2 (with the addition of making them properties which will be calculated when you first access them).



    class Img:
    def __init__(self,filename):
    self.name = filename
    self.image = Image.open(self.name) # open image using PIL

    # convert the image to a pandas df
    self.df = pd.DataFrame(data=list(self.image.getdata()))

    # get the RGB values from the image
    self.r = self.df[0].mean()
    self.g = self.df[1].mean()
    self.b = self.df[2].mean()

    self._luminance = None
    self._contrast = None

    @property
    def luminance(self):
    """Calculate luminance (brightness) based on the RGB values"""
    if self._luminance is None:
    self._luminance = (0.299*self.r + 0.587*self.g + 0.114*self.b)
    return self._luminance

    @property
    def contrast(self):
    """Calculate the contrast using the Michelson contrast formula."""
    if self._contrast is None:
    min_ = self.luminance.quantile(0.05)
    max_ = self.luminance.quantile(0.95)
    self._contrast = (max_ - min_) / (max_ + min_)
    return self._contrast





    share|improve this answer

























      up vote
      1
      down vote













      All those inner functions in your constructor are unnecessary. Inner functions should be used sparingly, normally you have only these cases:



      1. Functions which can do something based on parameters you pass to it and which are not directly related to some object. Make these functions stand-alone functions.

      2. Functions which do something with an object or return some information about that object. Make these functions methods (or properties) of the class of the object.

      3. Functions which logically belong to some class because they make only sense in combination with them. Make these functions static methods of the class (by adding the decorator @staticmethod).

      In your case I would do Option 2 (with the addition of making them properties which will be calculated when you first access them).



      class Img:
      def __init__(self,filename):
      self.name = filename
      self.image = Image.open(self.name) # open image using PIL

      # convert the image to a pandas df
      self.df = pd.DataFrame(data=list(self.image.getdata()))

      # get the RGB values from the image
      self.r = self.df[0].mean()
      self.g = self.df[1].mean()
      self.b = self.df[2].mean()

      self._luminance = None
      self._contrast = None

      @property
      def luminance(self):
      """Calculate luminance (brightness) based on the RGB values"""
      if self._luminance is None:
      self._luminance = (0.299*self.r + 0.587*self.g + 0.114*self.b)
      return self._luminance

      @property
      def contrast(self):
      """Calculate the contrast using the Michelson contrast formula."""
      if self._contrast is None:
      min_ = self.luminance.quantile(0.05)
      max_ = self.luminance.quantile(0.95)
      self._contrast = (max_ - min_) / (max_ + min_)
      return self._contrast





      share|improve this answer























        up vote
        1
        down vote










        up vote
        1
        down vote









        All those inner functions in your constructor are unnecessary. Inner functions should be used sparingly, normally you have only these cases:



        1. Functions which can do something based on parameters you pass to it and which are not directly related to some object. Make these functions stand-alone functions.

        2. Functions which do something with an object or return some information about that object. Make these functions methods (or properties) of the class of the object.

        3. Functions which logically belong to some class because they make only sense in combination with them. Make these functions static methods of the class (by adding the decorator @staticmethod).

        In your case I would do Option 2 (with the addition of making them properties which will be calculated when you first access them).



        class Img:
        def __init__(self,filename):
        self.name = filename
        self.image = Image.open(self.name) # open image using PIL

        # convert the image to a pandas df
        self.df = pd.DataFrame(data=list(self.image.getdata()))

        # get the RGB values from the image
        self.r = self.df[0].mean()
        self.g = self.df[1].mean()
        self.b = self.df[2].mean()

        self._luminance = None
        self._contrast = None

        @property
        def luminance(self):
        """Calculate luminance (brightness) based on the RGB values"""
        if self._luminance is None:
        self._luminance = (0.299*self.r + 0.587*self.g + 0.114*self.b)
        return self._luminance

        @property
        def contrast(self):
        """Calculate the contrast using the Michelson contrast formula."""
        if self._contrast is None:
        min_ = self.luminance.quantile(0.05)
        max_ = self.luminance.quantile(0.95)
        self._contrast = (max_ - min_) / (max_ + min_)
        return self._contrast





        share|improve this answer













        All those inner functions in your constructor are unnecessary. Inner functions should be used sparingly, normally you have only these cases:



        1. Functions which can do something based on parameters you pass to it and which are not directly related to some object. Make these functions stand-alone functions.

        2. Functions which do something with an object or return some information about that object. Make these functions methods (or properties) of the class of the object.

        3. Functions which logically belong to some class because they make only sense in combination with them. Make these functions static methods of the class (by adding the decorator @staticmethod).

        In your case I would do Option 2 (with the addition of making them properties which will be calculated when you first access them).



        class Img:
        def __init__(self,filename):
        self.name = filename
        self.image = Image.open(self.name) # open image using PIL

        # convert the image to a pandas df
        self.df = pd.DataFrame(data=list(self.image.getdata()))

        # get the RGB values from the image
        self.r = self.df[0].mean()
        self.g = self.df[1].mean()
        self.b = self.df[2].mean()

        self._luminance = None
        self._contrast = None

        @property
        def luminance(self):
        """Calculate luminance (brightness) based on the RGB values"""
        if self._luminance is None:
        self._luminance = (0.299*self.r + 0.587*self.g + 0.114*self.b)
        return self._luminance

        @property
        def contrast(self):
        """Calculate the contrast using the Michelson contrast formula."""
        if self._contrast is None:
        min_ = self.luminance.quantile(0.05)
        max_ = self.luminance.quantile(0.95)
        self._contrast = (max_ - min_) / (max_ + min_)
        return self._contrast






        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered Jun 7 at 13:11









        Graipher

        20.4k42981




        20.4k42981






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196021%2fclass-made-to-do-some-basic-rgb-analysis%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Chat program with C++ and SFML

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            Will my employers contract hold up in court?