Color extraction with Python + OpenCV solved the mystery of the green background

Purpose

150226-143939-screen-shot.jpg

I'm sorry for the image of Uncle Musai suddenly.

I tried, "Can I extract each of the four colored wooden balls of red, yellow, blue, and green?"

Both Python history and OpenCV history are about one month, so please point out my poor points (really).

Filter code

The following is

  1. Brighten the pixels (hTarget) of the specified hue (hue)
  2. Grayscale non-applicable pixels (hMask2)

The code.

filters.py


...

def hueMask(src, dst, hue, hueRange):
    src = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(src)
    hOrg = h.copy()
    hTarget = h.copy()

    cv2.threshold(hTarget, hue + hueRange, hue, cv2.THRESH_TOZERO_INV, hTarget)
    # 「src(x,y)If is greater than thresh, then dst(x,y)is 0"

    # 0
    # 0
    # 0
    # thresh
    # src
    # src
    # src
    # src
    # src

    cv2.threshold(hTarget, hue - hueRange, hue, cv2.THRESH_BINARY, hTarget)
    # 「src(x,y)If is less than thresh, dst(x,y)is 0"

    # 0(src)
    # 0(src)
    # 0(src)
    # src
    # src
    # thresh
    # 0
    # 0
    # 0

    #result

    # 0
    # 0
    # 0
    # thresh
    # src
    # thresh
    # 0
    # 0
    # 0

    #To exclude fluorescent light (yellow) and hair (blue)
    #Exclude extremely desaturated pixels from the target range
    sNotVeryLow = s.copy() #Where the saturation is not extremely low
    #If the saturation is higher than 31, put it in the target range (255).
    #Otherwise the non-target range (0).
    cv2.threshold(sNotVeryLow, 31, 255, cv2.THRESH_BINARY, sNotVeryLow)

    #The logical product of hTarget and vNotHighlight is new hTarget
    cv2.bitwise_and(hTarget, vNotVeryLow, hTarget)

    #Make a copy of the brightness image.
    vBrightened = v.copy()
    #in addition+Apply 96 gamma correction to make it brighter
    cv2.addWeighted(v, 0.625, v, 0.0, 96, vBrightened)
    #Insert a gamma-corrected brightness image only in the target range of the brightness image
    cv2.bitwise_and(vBrightened, 255, v, hTarget)

    hMask2 = h.copy()
    #When the corresponding pixel of hTarget (1 channel image) is 0
    #Set the corresponding pixel of hMask2 (1 channel image) to 255.
    #Otherwise, set it to 0.
    #In short, hMask2 is an inverted version of the hTarget mask image.
    cv2.compare(hTarget, 0, cv2.CMP_EQ, hMask2)

    cv2.bitwise_and(s, 0, s, hMask2) #Logical AND

    cv2.merge((hOrg, s, v), src)
    cv2.cvtColor(src, cv2.COLOR_HSV2BGR, dst)

...

Somehow the name of the variable is dirty, but ... Now you can extract any hue.

Application code

Next, try to extract four colors, that is, the hues of red, yellow, blue, and green.

App.py


...
class App(object):
    def __init__(self):
        ...
        self._shouldHueMask                = False
        ...
    def run(self):
        ...
        while self._windowManager.isWindowCreated:
            ...
            if self._shouldHueMask:
                filters.hueMask(frame, frame, self._hue, self._hueRange)
            ...
    def onKeypress(self, keycode):
        ...
        elif keycode == ord('B'): #Blue
            self._hue      = 110
            self._hueRange = 10
            self._shouldHueMask = \
                not self._shouldHueMask
        elif keycode == ord('G'): #Green
            self._hue      = 70
            self._hueRange = 25
            self._shouldHueMask = \
                not self._shouldHueMask
        elif keycode == ord('R'): #Red
            self._hue      = 5
            self._hueRange = 5
            self._shouldHueMask = \
                not self._shouldHueMask
        elif keycode == ord('Y'): #yellow
            self._hue      = 30
            self._hueRange = 15
            self._shouldHueMask = \
                not self._shouldHueMask
        ...
if __name__=="__main__":
    App().run()

The hue value and width of each of red, yellow, blue, and green were decided after trial and error.

result

Red

150226-144313-screen-shot.jpg

Well, it seems that the skin color has reacted to the "red extraction". With this, it is not possible to extract the wooden ball "only".

yellow

150226-144702-screen-shot.jpg

Well, this time the ceiling has reacted to the "yellow extraction".

Blue

150226-144944-screen-shot.jpg

This time the hair and the black sweater have reacted to the "blue extraction".

Green

150226-145207-screen-shot.jpg

I was able to extract the wooden balls most beautifully.

When compositing images, you stand in front of a green cloth called a green background. There is a reason why it was green.

The reason why green is soothing may be that the eyes feel comfortable with new stimuli, unlike the colors that appear in everyday life.

Maybe that's why the blackboard is green?

I will put the brush on it, leaving room for discussion.


I'm blogging: Weed.nagoya

Recommended Posts

Color extraction with Python + OpenCV solved the mystery of the green background
Fill the background with a single color with OpenCV2 + Python
2016 The University of Tokyo Mathematics Solved with Python
I tried "gamma correction" of the image with Python + OpenCV
Estimate the attitude of AR markers with Python + OpenCV + drone
Basic study of OpenCV with Python
Check the existence of the file with python
How to crop the lower right part of the image with Python OpenCV
Get and estimate the shape of the head using Dlib and OpenCV with python
Try to separate the background and moving object of the video with OpenCV
I tried "smoothing" the image with Python + OpenCV
Performance comparison of face detector with Python + OpenCV
Edge extraction with python + OpenCV (Sobel filter, Laplacian filter)
Color page judgment of scanned image with python
[Note] Export the html of the site with python.
Calculate the total number of combinations with python
Check the date of the flag duty with Python
I tried "binarizing" the image with Python + OpenCV
The easiest way to use OpenCV with python
Convert the character code of the file with Python3
[Python] Determine the type of iris with SVM
[Python + OpenCV] Whiten the transparent part of the image
Extract the table of image files with OneDrive & Python
Learn Nim with Python (from the beginning of the year).
Binarization with OpenCV / Python
Destroy the intermediate expression of the sweep method with Python
[OpenCV / Python] I tried image analysis of cells with OpenCV
[Python] Change the text color and background color of a specific keyword in print output
Try projective transformation of images using OpenCV with Python
the zen of Python
Visualize the range of interpolation and extrapolation with python
Calculate the regression coefficient of simple regression analysis with python
Write letters in the card illustration with OpenCV python
Summary of the basic flow of machine learning with Python
[Python] Summary of how to specify the color of the figure
Get the operation status of JR West with Python
[Windows] [Python] Camera calibration of fisheye lens with OpenCV
Visualize the appreciation status of art works with OpenCV
Extract the band information of raster data with python
Python Note: The mystery of assigning a variable to a variable
I tried "morphology conversion" of images with Python + OpenCV
I tried to find the entropy of the image with python
Try scraping the data of COVID-19 in Tokyo with Python
The story of implementing the popular Facebook Messenger Bot with python
Unify the environment of the Python development team starting with Poetry
Visualize the results of decision trees performed with Python scikit-learn
Calculate the square root of 2 in millions of digits with python
I wrote the basic grammar of Python with Jupyter Lab
Tank game made with python About the behavior of tanks
Run the intellisense of your own python library with VScode.
I evaluated the strategy of stock system trading with Python.
Check the scope of local variables with the Python locals function.
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo
Detect objects of a specific color and size with Python
The story of displaying images with OpenCV or PIL (only)
The story of rubyist struggling with python :: Dict data with pycall
[Homology] Count the number of holes in data with Python
Try to automate the operation of network devices with Python
Rewrite the record addition node of SPSS Modeler with Python.
Play with the password mechanism of GitHub Webhook and Python
[Python] Easy reading of serial number image files with OpenCV