• How to import image file as 2D array of RGB values using Python?
    6 replies, posted
Pseudocode: (thanks Fourier) [code]Image image = //import your image here, it is 2D array of RGB(A) values int width = image.width; int height = image.height; Node[][] graph = new Node[width][height]; //read image data for(var x = 0; x < width; x++) for(var y = 0; y < height; y++){ //and so on if(image[x][y].rgb == Color.roadColor) { graph.type == Type.Road; } else //... } [/code] So how do I go about turning this to actual Python code? How to import image as array of RGB colors? How to "image.width", "image.height", "image[x][y].rgb"?
i had a bunch of code here but then i was confused as to what your final goal is. why do you want an array of rgb colours? you're aware said array would be pixel data (and not very clean). i mean you can easily import an image with something like [code]import Image im = Image.open(path) [/code] if you have the python imaging library getting the height and width is then as simple as [code]width = im.size[0] height = im.size[1][/code]
I need pixel data. Goal can be seen in this thread: [url]http://facepunch.com/showthread.php?t=1427054[/url]
okay, to clarify, when you import an image with PIL you convert it to pixel data with im.load() then you browse it with [code]for x in range (im.size[0]): for y in range (im.size[1]): i = im.load()[/code] and then you just use i[x,y] to browse the pixel data (which is preset to be in RGB format) so you can just do something like [code]if i[23,523]<(255,255,255): print ("not white")[/code] python is very different to c++ as well, and your pseudocode looks like c++
Thanks. How do I reconstruct array back into image file?
if you edit the pixel data, it's instantly changed on the image file itself so there's no real need to convert the array.
I'm just going out on a limb here but maybe, just possibly, it could be im.save(filename) Try reading the PIL documentation If I were you though, I would use opencv instead of PIL.
Sorry, you need to Log In to post a reply to this thread.