質問

画像から特定の色を削除しようとしていますが、期待どおりに機能していません。私はここで見たのと同じことをやろうとしました PILを使用してすべて白にするピクセルは透明ですか?ただし、画質は少し劣化しているため、削除された部分の周りに奇妙な色のピクセルのゴーストが残ります。 3つすべての値が100未満の場合、ピクセルを変更するようなことを試みましたが、画像の品質が低いため、周囲のピクセルは黒でさえありませんでした。

PythonでPILを使用して、色とそれを囲むものを置き換えるより良い方法を知っている人はいますか?これはおそらく、オブジェクトを完全に削除するために考えられる唯一の確実な方法ですが、これを行う方法は考えられません。

画像の背景は白で、テキストは黒です。アーティファクトを残さずに画像からテキストを完全に削除したいとします。

誰かの助けに本当に感謝します!ありがとう

役に立ちましたか?

解決

画像を2次元配列として表す必要があります。これは、ピクセルのリストのリストを作成するか、1次元配列を巧妙な数学で2次元配列として表示することを意味します。次に、対象となるピクセルごとに、周囲のすべてのピクセルを見つける必要があります。 Pythonジェネレーターでこれを行うことができます:

def targets(x,y):
    yield (x,y) # Center
    yield (x+1,y) # Left
    yield (x-1,y) # Right
    yield (x,y+1) # Above
    yield (x,y-1) # Below
    yield (x+1,y+1) # Above and to the right
    yield (x+1,y-1) # Below and to the right
    yield (x-1,y+1) # Above and to the left
    yield (x-1,y-1) # Below and to the left

したがって、次のように使用します:

for x in range(width):
    for y in range(height):
        px = pixels[x][y]
        if px[0] == 255 and px[1] == 255 and px[2] == 255:
            for i,j in targets(x,y):
                newpixels[i][j] = replacementColor

他のヒント

それを行う最良の方法は、<!> quot; color to alpha <!> quot;を使用することです。色を置き換えるために Gimp で使用されるアルゴリズム。それはあなたの場合に完全に機能します。オープンソースのPythonフォトプロセッサ phatch にPILを使用してこのアルゴリズムを再実装しました。完全な実装を見つけることができますここ。これは純粋なPIL実装であり、他の依存関係はありません。機能コードをコピーして使用できます。 Gimpを使用したサンプルは次のとおりです。

alt textから alt text

色として黒を使用して、画像にcolor_to_alpha関数を適用できます。次に、画像を別の背景色に貼り付けて置き換えます。

ところで、この実装はPILのImageMathモジュールを使用します。 getdataを使用してピクセルにアクセスするよりもはるかに効率的です。

編集:完全なコードは次のとおりです:

from PIL import Image, ImageMath

def difference1(source, color):
    """When source is bigger than color"""
    return (source - color) / (255.0 - color)

def difference2(source, color):
    """When color is bigger than source"""
    return (color - source) / color


def color_to_alpha(image, color=None):
    image = image.convert('RGBA')
    width, height = image.size

    color = map(float, color)
    img_bands = [band.convert("F") for band in image.split()]

    # Find the maximum difference rate between source and color. I had to use two
    # difference functions because ImageMath.eval only evaluates the expression
    # once.
    alpha = ImageMath.eval(
        """float(
            max(
                max(
                    max(
                        difference1(red_band, cred_band),
                        difference1(green_band, cgreen_band)
                    ),
                    difference1(blue_band, cblue_band)
                ),
                max(
                    max(
                        difference2(red_band, cred_band),
                        difference2(green_band, cgreen_band)
                    ),
                    difference2(blue_band, cblue_band)
                )
            )
        )""",
        difference1=difference1,
        difference2=difference2,
        red_band = img_bands[0],
        green_band = img_bands[1],
        blue_band = img_bands[2],
        cred_band = color[0],
        cgreen_band = color[1],
        cblue_band = color[2]
    )

    # Calculate the new image colors after the removal of the selected color
    new_bands = [
        ImageMath.eval(
            "convert((image - color) / alpha + color, 'L')",
            image = img_bands[i],
            color = color[i],
            alpha = alpha
        )
        for i in xrange(3)
    ]

    # Add the new alpha band
    new_bands.append(ImageMath.eval(
        "convert(alpha_band * alpha, 'L')",
        alpha = alpha,
        alpha_band = img_bands[3]
    ))

    return Image.merge('RGBA', new_bands)

image = color_to_alpha(image, (0, 0, 0, 255))
background = Image.new('RGB', image.size, (255, 255, 255))
background.paste(image.convert('RGB'), mask=image)

numpyとPILの使用:

これは、イメージをシェイプ(W,H,3)のnumpy配列にロードします。ここで、Wは 幅とHは高さです。配列の3番目の軸は3色を表します チャネル、R,G,B

import Image
import numpy as np

orig_color = (255,255,255)
replacement_color = (0,0,0)
img = Image.open(filename).convert('RGB')
data = np.array(img)
data[(data == orig_color).all(axis = -1)] = replacement_color
img2 = Image.fromarray(data, mode='RGB')
img2.show()

orig_colorは長さ3のタプルであり、dataは 形状data == orig_color、NumPy ブロードキャスト (data == orig_color).all(axis = -1)を形状(W,H)の配列に変換して、比較original_colorを実行します。結果は、形状<=>のブール配列になります。

<=>は形状<=>のブール配列で、 <=>のRGBカラーが<=>である場合は常にTrueです。

#!/usr/bin/python
from PIL import Image
import sys

img = Image.open(sys.argv[1])
img = img.convert("RGBA")

pixdata = img.load()

# Clean the background noise, if color != white, then set to black.
# change with your color
for y in xrange(img.size[1]):
    for x in xrange(img.size[0]):
        if pixdata[x, y] == (255, 255, 255, 255):
            pixdata[x, y] = (0, 0, 0, 255)

ピクセルが簡単に識別できない場合、たとえば(r <!> lt; 100 and g <!> lt; 100 and b <!> lt; 100)また、黒い領域と正しく一致しない場合は、ノイズが多い。

最良の方法は、領域を識別し、必要な色で塗りつぶすことです。領域を手動で識別することができます。 http://bitecode.co.uk/2008/07/edge -detection-in-python /

またはより洗練されたアプローチは、opencv( http://opencv.willowgarage.com/のようなライブラリを使用することです。 wiki / )でオブジェクトを識別します。

これは私のコードの一部であり、結果は次のようになります。 ソース

ターゲット

import os
import struct
from PIL import Image
def changePNGColor(sourceFile, fromRgb, toRgb, deltaRank = 10):
    fromRgb = fromRgb.replace('#', '')
    toRgb = toRgb.replace('#', '')

    fromColor = struct.unpack('BBB', bytes.fromhex(fromRgb))
    toColor = struct.unpack('BBB', bytes.fromhex(toRgb))

    img = Image.open(sourceFile)
    img = img.convert("RGBA")
    pixdata = img.load()

    for x in range(0, img.size[0]):
        for y in range(0, img.size[1]):
            rdelta = pixdata[x, y][0] - fromColor[0]
            gdelta = pixdata[x, y][0] - fromColor[0]
            bdelta = pixdata[x, y][0] - fromColor[0]
            if abs(rdelta) <= deltaRank and abs(gdelta) <= deltaRank and abs(bdelta) <= deltaRank:
                pixdata[x, y] = (toColor[0] + rdelta, toColor[1] + gdelta, toColor[2] + bdelta, pixdata[x, y][3])

    img.save(os.path.dirname(sourceFile) + os.sep + "changeColor" + os.path.splitext(sourceFile)[1])

if __name__ == '__main__':
    changePNGColor("./ok_1.png", "#000000", "#ff0000")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top