by cidquick · 13y ago · 0 comments
RGB to grayscale: V = r x g x b/3 (one line).
The Sobel operation is at most 4 nested loops (really only 3) for a total of ~7 lines of code, depending on how you like your white space.
Fold the summation into your Sobel function without requiring another line.
The most complicated thing used from the OpenCV library (which I'm well aware is C++!) is JPEG decoding. OK, I'm avoiding swirling, but then it isn't needed to solve the CAPTCHA anyway.
Oh, BTW, "V = r x g x b/3" is incorrect. This is not you convert a color image to a grayscale image.
gray = map(lambda p:sum(p)/3,IMG)
If you want to test it, you can use this 3x3 sample image (or just load one): IMG = [[5, 5, 5], [6, 8, 9], [94, 123, 4], [54, 5, 32], [44, 3, 3], [34, 234, 33], [5, 5, 5], [6, 8, 9], [94, 123, 4]]
The result will look like this: [5, 7, 73, 30, 16, 100, 5, 7, 73]
If your image happens to be loaded into a 2-dimensional array, use this: gray = map(lambda row:map(lambda p:sum(p)/3,row), IMG)
Sobel is slightly more complicated, but can be written like this (you'll need a larger sample image though): width, height #width and height of our image
IMG #2D array of our RGB values
sobel #result image
# The actual filter starts here:
for x in range(1,width-1):
for y in range(1,height-1):
sx = IMG[x-1][y-1]+IMG[x][y-1]*2+IMG[x+1][y-1]-IMG[x-1][y+1]-IMG[x][y+1]*2-IMG[x+1][y+1]
sy = IMG[x+1][y-1]+IMG[x+1][y]*2+IMG[x+1][y+1]-IMG[x-1][y-1]-IMG[x-1][y]*2-IMG[x-1][y+1]
sobel[x][y] = Math.sqrt(sx*sx+sy*sy)
A total of 5 lines.
And I have to thank you, because I finally just learned what convolutions are while doing this.Just one quick observation. You can't convert from RGB to grayscale by simply averaging the three values. Each color channel influences the perceived luminance (grayscale) differently, with green being, by far, the largest component and blue the least significant. Rather than give you the answer I'd suggest you research "converting RGB to grayscale" or "converting RGB to luminance" as this is an important subject to understand if you are dealing with images.
I'll take a look at the rest of it later and comment.
> You can't convert from RGB to grayscale by simply averaging the three values
Of course I can
Edit: I just googled "RGB to grayscale" and this was the first result: http://www.johndcook.com/blog/2009/08/24/algorithms-convert-...
I recommend reading it