3

オブジェクトをクリックして、以前に選択した色のピクセル座標を取得したいと思います。このコードはインターネットで見つけました

import cv
tolerancia = 30
def evento_mouse(event,x,y,flags,param):
    if event==cv.CV_EVENT_LBUTTONDOWN:
        pixel=cv.Get2D(imagen,y,x) 
        print 'X =',x,'  Y =',y
        print 'R =',pixel[2],'G =',pixel[1],'B =',pixel[0]
        cv.InRangeS(imagen,(pixel[0]-tolerancia,pixel[1]-tolerancia,pixel[2]-                                               tolerancia),(pixel[0]+tolerancia,pixel[1]+tolerancia,pixel[2]+tolerancia),temporal)
        cv.ShowImage('Color',temporal)
        c = cv.Get2D(temporal,y,x) 
        print c[0],c[1],c[2] # I always get: 255, 0, 0
   imagen=cv.LoadImage('prueba2.png')
   cv.ShowImage('Prueba',imagen)
   temporal=cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1)
   cv.SetMouseCallback('Prueba',evento_mouse)
   cv.WaitKey(0)

ピクセルが白か黒かを確認しようとしています。しかし、私は常に同じ値を取得します: 255, 0, 0 (青 = 255)

4

2 に答える 2

3

理解する必要があることがいくつかあります。

OpenCV の古い 'cv' インターフェイスを使用しています。その場合、ピクセル値を取得するには、対応する BGR 値のタプルを返す関数 'cv2.Get2D' を使用します。

1. バイナリ イメージの場合、なぜ青色、つまり (255,0,0) なのですか?

カラー画像とグレースケール/バイナリ画像の両方で、3 つの要素の同じタプルが返されますが、グレースケール画像の場合、最初の要素はピクセル値であり、残りの 2 つは無関係であるため、ゼロです。したがって、バイナリ イメージ (時間) のピクセル値を読み取っているため、(255,0,0) などの値が得られます。

2. なぜ常に (255,0,0) なのか?

元の画像をクリックすると、対応するバイナリ画像が作成され、クリックした色に対応する領域が白になり、他のすべての領域が黒になります。元の画像の赤い色をクリックすると、バイナリ画像は、すべての赤い領域が白になり、黒のままになります。明らかに、クリックしたピクセルは常に白です。したがって、バイナリ イメージからそのピクセルを読み取ると、常に (255,0,0) しか得られません。

OpenCV の新しい Python インターフェイスである「cv2」モジュールに移行することをお勧めします。多くの利点があります。主な利点は、大きな問題である Numpy のサポートです。この SOF を比較して確認できます:これらすべての OpenCV Python インターフェイスの違いは何ですか?

また、ここから cv2 のスタートアップ チュートリアルを入手することもできます: www.opencvpython.blogspot.com

于 2012-10-20T05:02:17.173 に答える
0

まず、下限と上限が 0 から 255 の範囲内にあることを確認する必要があると思います。

次に、「一時的な」変数は「マスク」です。その位置のピクセル値が下限と上限の範囲内にある場合、位置 (x, y) で 255 に設定されます。指定された範囲内にあるすべてのピクセルが含まれているわけではありません。

以下は、テスト画像で試したコードです。いくつかの numpy を使用しましたが、コードに一致するように cv2.cv.fromarray() を使用して CvMat に変換したことに注意してください。

#!/usr/bin/env python

import cv2
import numpy as np

def main():
    image = cv2.imread("forest.jpg")
    imageMat = cv2.cv.fromarray(image)
    dst = cv2.cv.fromarray(np.zeros((imageMat.rows, imageMat.cols), np.uint8))

    x = 250 # Manually set pixel location. You can get this from your mouse event handler.
    y = 500
    pixel = image[y, x] # Note y index "row" of matrix and x index "col".
    tolerance = 10
    # Ensure your bounds are within 0 and 255.
    lower = tuple(map(lambda x: int(max(0, x - tolerance)), pixel))
    upper = tuple(map(lambda x: int(min(255, x + tolerance)), pixel))
    # Get mask of all pixels that satisfy range condition and store it in dst.
    cv2.cv.InRangeS(imageMat, lower, upper, dst)

    mask = np.asarray(dst) # Convert back to numpy array.
    cv2.imshow("Mask", mask) # The mask indicating which pixels satisfy range conditions
    cv2.imshow("Image", image)
    extracted = np.zeros_like(image) # The pixels that satisfy range condition.
    extracted[np.where(mask)] = image[np.where(mask)]
    cv2.imshow("extracted", extracted)

    cv2.waitKey()

if __name__ == "__main__":
    main()

そして、これは python2 バージョンです:

#!/usr/bin/env python

import cv2
import numpy as np

def main():
    image = cv2.imread("forest.jpg")
    x = 230 # Manually set pixel location. You can get this from your mouse event handler.
    y = 300
    pixel = image[y, x] # Note y index "row" of matrix and x index "col".
    tolerance = 30
    # Ensure your bounds are within 0 and 255.
    lower = map(lambda x: max(0, x - tolerance), pixel)
    upper = map(lambda x: min(255, x + tolerance), pixel)
    lower = np.asarray(lower)
    upper = np.asarray(upper)
    mask = cv2.inRange(image, lower, upper) # Notice we can just get mask without having to allocate it beforehand.

    cv2.imshow("Mask", mask) # The mask indicating which pixels satisfy range conditions
    cv2.imshow("Image", image)
    extracted = np.zeros_like(image) # The pixels that satisfy range condition.
    extracted[np.where(mask)] = image[np.where(mask)]
    cv2.imshow("extracted", extracted)

    cv2.waitKey()

if __name__ == "__main__":
    main()
于 2012-10-20T04:42:58.727 に答える