Detect color and remove that color from image

前端 未结 2 1078
北荒
北荒 2021-01-07 03:36

I have image with kind of light purple image in background and character in dark blue. My goal is to identify text from the image. So I\'m trying to remove light purple colo

2条回答
  •  执笔经年
    2021-01-07 03:53

    Here is an approach using a pixel array. Pixel arrays are slow, but if speed isn't an issue, they could serve your needs without having to download any outside libraries. Also, pixel arrays are easy to understand.

    import pygame
    # -- You would load your image as a sprite here. --
    # -- But let's create a demonstration sprite instead.--
    #
    usecolor = (46,12,187,255)       # Declare an example color.
    sprite = pygame.Surface((10,10)) # Greate a surface. Let us call it a 'sprite'.
    sprite.fill(usecolor)            # Fill the 'sprite' with our chosen color.
    #
    # -- Now process the image. --
    array = pygame.PixelArray(sprite)   # Create a pixel array of the sprite, locking the sprite.
    sample = array[5,5]                 # Sample the integer holding the color values of pixel [5,5]
                                        # We will feed this integer to pygame.Color()
    sample_1 = sprite.get_at((5,5))     # Alternately, we can use the .get_at() method.
    # Do the same for every pixel, creating a list (an array) of color values.
    del array                           # Then delete the pixel array, unlocking the sprite.
    
    m,r,g,b = pygame.Color(sample) # Note: m is for the alpha value (not used by .Color()) 
    
    print("\n sample =",sample,"decoded by python.Color() to:")
    print(" r >>",r)
    print(" g >>",g)
    print(" b >>",b)
    print("\n or we could use .get_at()")
    print(" sample_1 =",sample_1)
    print()
    exit()
    

    Just test each r,g,b value to see if they fall within some desired range for each color component. Then copy each pixel over to a new surface, replacing all colors that fall within your range with your desired replacement color.

    Or you could add, say 75 to each R,G,B color component (if color > 255: color = 255) before placing the pixel in the new image. This would have the effect of fading all colors towards white until the light color is gone. Then you could repeat the process subtracting 75 from each remaining pixel (with component values less than 255) to bring the colors forward again. I doubt any decent captcha is so easily defeated, but there you go.

    Fun fun!

提交回复
热议问题