{
  "id": 6827,
  "title": "Reading Image files",
  "url": "/competitions/galaxy-zoo-the-galaxy-challenge/discussion/6827",
  "author_name": "",
  "post_date": "2014-01-13T16:42:23.030Z",
  "votes": null,
  "comment_count": 4,
  "views": 2813,
  "content": "<p>Hi everyone,</p>\n<p>I am using this competition to get familiar with image processing but am stuck at the very start. I am using python to read the images and vectorize them but I get an error saying &quot;too many open files&quot; when I try stacking them. Am sure most of you here couldhelp me with this, is it a memory issue with my system or can I code efficiently to avoid this?</p>\n<p>&nbsp;</p>\n<p>Help appreciated!!</p>\n<p>Thanks,</p>\n<p>MB</p>",
  "messages": [
    {
      "id": "37353",
      "postDate": "01/13/2014 16:42:23",
      "content": "<p>Hi everyone,</p>\n<p>I am using this competition to get familiar with image processing but am stuck at the very start. I am using python to read the images and vectorize them but I get an error saying &quot;too many open files&quot; when I try stacking them. Am sure most of you here couldhelp me with this, is it a memory issue with my system or can I code efficiently to avoid this?</p>\n<p>&nbsp;</p>\n<p>Help appreciated!!</p>\n<p>Thanks,</p>\n<p>MB</p>",
      "rawMarkdown": "",
      "votes": null
    },
    {
      "id": "37355",
      "postDate": "01/13/2014 19:22:50",
      "content": "<p>What do you mean with stacking images?</p>\n<p>Here is some Python and PIL code to read images in a directory, one by one, cropping the images center-center to 140px * 140px, convert to grayscale, pixelate that image to 5px * 5px blocks (taking average of the 25 pixels that make up a block), then vectorizes these blocks to floats ranging between 0 and 1. For now it outputs a file with on every line: the image id followed by a list of tuples with feature id (0-783) and feature value (float between 0-1).</p>\n<p>I hope this gets you started vectorizing images without running into memory problems. This code is still fairly slow (about 100 images a second). If you are looking for increased speed,&nbsp;Numpy can vectorize images a lot faster.</p>\n<p><code>#imports<br>from PIL import Image<br>import glob<br>import os</code></p>\n<p><code>#main script variables<br>pixelSize = 5<br>crop_dimensions = (140, 140, 284, 284)<br>glob_files = &quot;kaggle_space/images_test/*.jpg&quot;<br>vector_file = &quot;kaggle_space/imagevectors.txt&quot; #will be created<br>nr_docs = len(glob.glob(glob_files))</code></p>\n<p><code>#open a file to store our vectors<br>with open(vector_file, &quot;wb&quot;) as outfile:<br>&nbsp; for enum, infile in enumerate( glob.glob(glob_files) ):<br> </code></p>\n<p><code>&nbsp; &nbsp; #open image and get the filename and extension<br>&nbsp; &nbsp; image = Image.open(infile)<br>&nbsp; &nbsp; filen, ext = os.path.splitext(infile)<br>&nbsp; &nbsp; file_id = filen[-6:]<br> </code></p>\n<p><code>&nbsp; &nbsp; # take out interesting part in the center-center, leaves 140x140 image<br>&nbsp; &nbsp; image = image.crop(crop_dimensions)<br> </code></p>\n<p><code>&nbsp; &nbsp; # convert to grayscale 0-256<br>&nbsp; &nbsp; image = image.convert('L')<br> </code></p>\n<p><code>&nbsp; &nbsp; # pixelate the image with pixelSize<br>&nbsp; &nbsp; image = image.resize((image.size[0]/pixelSize,</code></p>\n<p><code>image.size[1]/pixelSize), Image.NEAREST)<br>&nbsp; &nbsp; image = image.resize((image.size[0]*pixelSize, image.size[1]*pixelSize), Image.NEAREST)<br> </code></p>\n<p><code>&nbsp; &nbsp; # load resulting pixel data<br>&nbsp; &nbsp; pixel = image.load()<br> </code></p>\n<p><code>&nbsp; &nbsp; # convert every pixelated block to a 0-1 float<br>&nbsp; &nbsp; u = 0<br>&nbsp; &nbsp; vectors = []<br>&nbsp; &nbsp; for i in xrange(0,image.size[0],pixelSize):<br>&nbsp; &nbsp; &nbsp; for y in xrange(0,image.size[1],pixelSize):<br>&nbsp; &nbsp; &nbsp; &nbsp; vectors.append( (u, round(pixel[y, i]/float(255),3)) )<br>&nbsp; &nbsp; &nbsp; &nbsp; u += 1<br> </code></p>\n<p><code>&nbsp; &nbsp; #write vectors to file (or format as libSVM or whatever)<br>&nbsp; &nbsp; outfile.write(str(file_id) + &quot; &quot; + str(vectors) + &quot;\\n&quot;)<br> </code></p>\n<p><code>&nbsp; &nbsp; #status report<br>&nbsp; &nbsp; if enum % 100 == 0:<br>&nbsp; &nbsp; &nbsp; print enum</code></p>",
      "rawMarkdown": "",
      "votes": null
    },
    {
      "id": "37379",
      "postDate": "01/14/2014 15:43:12",
      "content": "<p>I was using vstack to vertically stack images but this is more than helpful, thanks a lot&nbsp;Triskelion!!</p>",
      "rawMarkdown": "",
      "votes": null
    },
    {
      "id": "37639",
      "postDate": "01/20/2014 14:52:32",
      "content": "<p>Thanks a lot Triskelion. &nbsp;Managed to run your code and get the features for a couple of trial images. &nbsp;Would be great if you can provide some pointers to code for the following:</p>\n<p>1. Is there someway to construct the images from the vectors - want to make sure that I am vectorizing correctly. &nbsp;</p>\n<p>2. The file contains the feature id and the feature value in parenthesis. I want to load a matrix containing just the features to some tool like Octave/R. &nbsp;Is there some ready code which will convert the generated text file to CSV or some other format which I can load using elementary commands.</p>\n<p>It would be great if you can provide pointers to code doing these. &nbsp;Understand these might be simple... but I have never done image processing or coding in Python. &nbsp;This is my first attempt after learning some basic stuff through coursera.</p>",
      "rawMarkdown": "",
      "votes": null
    },
    {
      "id": "37719",
      "postDate": "01/22/2014 11:04:13",
      "content": "<p>1. You should be able to convert the vectors back to pixel values by multiplying them by 255. Then read up on PIL on how to save a list of pixel values to an image.</p>\n<p>If you just want to see the resulting pixelated image try image.save(&quot;test.jpg&quot;) just before #load resulting pixel data.</p>\n<p>2. Would be best to use a csv writer for that. Quick hack, change this line:</p>\n<p>vectors.append( (u, round(pixel[y, i]/float(255),3)) )</p>\n<p>to:&nbsp;</p>\n<p>vectors.append( str(round(pixel[y, i]/float(255),3)) )</p>\n<p>Then change this line:</p>\n<p>outfile.write(str(file_id) + &quot; &quot; + str(vectors) + &quot;\\n&quot;)</p>\n<p>to:</p>\n<p>outfile.write(str(file_id) + &quot;,&quot; + &quot;,&quot;.join(vectors) + &quot;\\n&quot;)</p>\n<p>Not tested, but this should create a CSV-file without a header. Try if it works, if not, I'll test myself and provide proper code.</p>",
      "rawMarkdown": "",
      "votes": null
    }
  ],
  "comments": [
    {
      "id": 37355,
      "author_name": "triskelion",
      "author_url": "",
      "post_date": "01/13/2014 19:22:50",
      "content": "<p>What do you mean with stacking images?</p>\n<p>Here is some Python and PIL code to read images in a directory, one by one, cropping the images center-center to 140px * 140px, convert to grayscale, pixelate that image to 5px * 5px blocks (taking average of the 25 pixels that make up a block), then vectorizes these blocks to floats ranging between 0 and 1. For now it outputs a file with on every line: the image id followed by a list of tuples with feature id (0-783) and feature value (float between 0-1).</p>\n<p>I hope this gets you started vectorizing images without running into memory problems. This code is still fairly slow (about 100 images a second). If you are looking for increased speed,&nbsp;Numpy can vectorize images a lot faster.</p>\n<p><code>#imports<br>from PIL import Image<br>import glob<br>import os</code></p>\n<p><code>#main script variables<br>pixelSize = 5<br>crop_dimensions = (140, 140, 284, 284)<br>glob_files = &quot;kaggle_space/images_test/*.jpg&quot;<br>vector_file = &quot;kaggle_space/imagevectors.txt&quot; #will be created<br>nr_docs = len(glob.glob(glob_files))</code></p>\n<p><code>#open a file to store our vectors<br>with open(vector_file, &quot;wb&quot;) as outfile:<br>&nbsp; for enum, infile in enumerate( glob.glob(glob_files) ):<br> </code></p>\n<p><code>&nbsp; &nbsp; #open image and get the filename and extension<br>&nbsp; &nbsp; image = Image.open(infile)<br>&nbsp; &nbsp; filen, ext = os.path.splitext(infile)<br>&nbsp; &nbsp; file_id = filen[-6:]<br> </code></p>\n<p><code>&nbsp; &nbsp; # take out interesting part in the center-center, leaves 140x140 image<br>&nbsp; &nbsp; image = image.crop(crop_dimensions)<br> </code></p>\n<p><code>&nbsp; &nbsp; # convert to grayscale 0-256<br>&nbsp; &nbsp; image = image.convert('L')<br> </code></p>\n<p><code>&nbsp; &nbsp; # pixelate the image with pixelSize<br>&nbsp; &nbsp; image = image.resize((image.size[0]/pixelSize,</code></p>\n<p><code>image.size[1]/pixelSize), Image.NEAREST)<br>&nbsp; &nbsp; image = image.resize((image.size[0]*pixelSize, image.size[1]*pixelSize), Image.NEAREST)<br> </code></p>\n<p><code>&nbsp; &nbsp; # load resulting pixel data<br>&nbsp; &nbsp; pixel = image.load()<br> </code></p>\n<p><code>&nbsp; &nbsp; # convert every pixelated block to a 0-1 float<br>&nbsp; &nbsp; u = 0<br>&nbsp; &nbsp; vectors = []<br>&nbsp; &nbsp; for i in xrange(0,image.size[0],pixelSize):<br>&nbsp; &nbsp; &nbsp; for y in xrange(0,image.size[1],pixelSize):<br>&nbsp; &nbsp; &nbsp; &nbsp; vectors.append( (u, round(pixel[y, i]/float(255),3)) )<br>&nbsp; &nbsp; &nbsp; &nbsp; u += 1<br> </code></p>\n<p><code>&nbsp; &nbsp; #write vectors to file (or format as libSVM or whatever)<br>&nbsp; &nbsp; outfile.write(str(file_id) + &quot; &quot; + str(vectors) + &quot;\\n&quot;)<br> </code></p>\n<p><code>&nbsp; &nbsp; #status report<br>&nbsp; &nbsp; if enum % 100 == 0:<br>&nbsp; &nbsp; &nbsp; print enum</code></p>",
      "votes": null,
      "replies": []
    },
    {
      "id": 37379,
      "author_name": "gauravtaneja",
      "author_url": "",
      "post_date": "01/14/2014 15:43:12",
      "content": "<p>I was using vstack to vertically stack images but this is more than helpful, thanks a lot&nbsp;Triskelion!!</p>",
      "votes": null,
      "replies": []
    },
    {
      "id": 37639,
      "author_name": "ratheesh",
      "author_url": "",
      "post_date": "01/20/2014 14:52:32",
      "content": "<p>Thanks a lot Triskelion. &nbsp;Managed to run your code and get the features for a couple of trial images. &nbsp;Would be great if you can provide some pointers to code for the following:</p>\n<p>1. Is there someway to construct the images from the vectors - want to make sure that I am vectorizing correctly. &nbsp;</p>\n<p>2. The file contains the feature id and the feature value in parenthesis. I want to load a matrix containing just the features to some tool like Octave/R. &nbsp;Is there some ready code which will convert the generated text file to CSV or some other format which I can load using elementary commands.</p>\n<p>It would be great if you can provide pointers to code doing these. &nbsp;Understand these might be simple... but I have never done image processing or coding in Python. &nbsp;This is my first attempt after learning some basic stuff through coursera.</p>",
      "votes": null,
      "replies": []
    },
    {
      "id": 37719,
      "author_name": "triskelion",
      "author_url": "",
      "post_date": "01/22/2014 11:04:13",
      "content": "<p>1. You should be able to convert the vectors back to pixel values by multiplying them by 255. Then read up on PIL on how to save a list of pixel values to an image.</p>\n<p>If you just want to see the resulting pixelated image try image.save(&quot;test.jpg&quot;) just before #load resulting pixel data.</p>\n<p>2. Would be best to use a csv writer for that. Quick hack, change this line:</p>\n<p>vectors.append( (u, round(pixel[y, i]/float(255),3)) )</p>\n<p>to:&nbsp;</p>\n<p>vectors.append( str(round(pixel[y, i]/float(255),3)) )</p>\n<p>Then change this line:</p>\n<p>outfile.write(str(file_id) + &quot; &quot; + str(vectors) + &quot;\\n&quot;)</p>\n<p>to:</p>\n<p>outfile.write(str(file_id) + &quot;,&quot; + &quot;,&quot;.join(vectors) + &quot;\\n&quot;)</p>\n<p>Not tested, but this should create a CSV-file without a header. Try if it works, if not, I'll test myself and provide proper code.</p>",
      "votes": null,
      "replies": []
    }
  ],
  "raw_markdown_by_id": {
    "37353": "",
    "37355": "",
    "37379": "",
    "37639": "",
    "37719": ""
  },
  "source": "meta"
}