Happy
Happy

Reputation: 469

Translating Python PIL code to Python OpenCV

I'm doing some amateur image analysis using Python, specifically Numpy, PIL and OpenCV. However, I'm not too pleased with the performance of PIL, so I would like to port those parts of the code to OpenCV. This will also make it easier to port the code to C/C++ later on, if needed.

Anyways, I'm having some trouble with porting parts of my code, and would love some help here. Specifically, the parts I need changed is:

Function: Find the red, green and blue (R,G,B) intensity with the most pixels in the image. Currently done through the histogram. Input image is in the form of a Python PIL image.

def bgcalcRGB(img):

    hist = img.histogram()

    R=0;G=0;B=0; avgR=0.; avgG=0.; avgB=0.; Rmax=175+15; Rmin=175-15;
    Gmax=160+15; Gmin=160-15; Bmax=150+15; Bmin=150-15;

    for x in range(Rmin,Rmax,1):
        if hist[x] > avgR: avgR = hist[x]; R = x
    for x in range(256+Gmin,Gmax+256,1):
        if hist[x] > avgG: avgG = hist[x]; G = x - 256
    for x in range(256*2+Bmin,Bmax+256*2,1):
        if hist[x] > avgB: avgB = hist[x]; B = x - 256*2
    return (R,G,B)

Function: Serves as a simultaneous threshold of the RGB channals. If a certain RGB pixel is within a certain range (independent for R,G and B), it is coloured white. If not, it is discarded and coloured black. Input image is a Python PIL image.

def mask(low, high):
    return [255 if low <= x <= high else 0 for x in range(0, 256)]

img1 = img.point(mask(val1-uc1,val1+uc1)+mask(val2-uc2,val2+uc2)+mask(val3-uc2,val2+uc2)).convert('L').point([0]*255+[255]).convert('RGB')

So what I need is help with translating the above code to using only OpenCV, or at least not using Python PIL.

Thanks!

Upvotes: 0

Views: 1077

Answers (1)

Froyo
Froyo

Reputation: 18477

you should try SimpleCV

It is based on Python OpenCV bindings, scipy, numpy, pygame, PIL. SimpleCV is very easy to learn and implement.

img = Image("filename.jpg") will load the image in BGR form.

To access x, y pixel of the image, color = img[x, y]

to get cv2.cv.iplimage => img.getBitmap()

SimpleCV integrates scipy and numpy for fast computation and Machine Learning moduels. It includes pygame display.

To display the image, img.show()

It also includes various tracknig features(Lucas Kanade Tracker, CAMShift, etc), keypoint match features(SURF, SIFT, ASIFT, STAR, ORB, MSER, etc), and many other blob features.

Basic Image Processing and image data extraction can be easily done using SimpleCV.

Upvotes: 1

Related Questions