Hi,

I have an application where I need to load images present in a folder onto my Visual Studio application. As in if I have a folder named temp and I have say 5 images temp1-temp5 inside the folder temp, i need to load each of the images temp1-temp5 (in an iterative fashion) and perform some operations on it. Can someone give me an idea as to how to do this

Thanks

Prashanth

Hiya,

Something like this:

string folderPath = @"C:\Users\Dan\Pictures";
            string[] fileList = Directory.GetFiles(folderPath);
            foreach (string file in fileList)
            {
                //do something to file
                //'file' contains path as string
            }

or if you want to select a folder at run time you can look at a FolderBrowserDialog rather than hardcoding the directory location.

If there may be other files in there you can add some validation by either adding a search string Directory.GetFiles(folderPath, "*.jpg") or by checking inside the foreach loop

foreach (string file in fileList)
            {
                if (file.Contains(".jpg"))
                {
                    //do something to file
                    //'file' contains path as string
                }
            }

Thanx man.. Well reg choosing files during run time, I am aware of how to do this. Its just that I was not sure how to use the GetFiles function.

Thanks anyways

Hi, I tried using your logic and it seemed to work fine. But when I give the following code, I get an error :

string[] files = Directory.GetFiles(@"C:\Users\pashok\Documents\test\image0089\","*.jpg");
            string filename;
            int index;
            foreach (string file in files)
            {
                pictureBox1.ImageLocation = file;
               //rest of the code

The problem is with the last image in the folder, where I get an error message : Object reference not set to an instance of an object.

Can someone help me overcome it

To make things clear :

        file    "C:\\Users\\pashok\\Documents\\test\\image0089\\Image_2.jpg"    string
+       pictureBox1 {System.Windows.Forms.PictureBox, SizeMode: Normal} System.Windows.Forms.PictureBox
        pictureBox1.Image   null    System.Drawing.Image
        pictureBox1.ImageLocation   "C:\\Users\\pashok\\Documents\\test\\image0089\\Image_2.jpg"    string
+       srcImage    null    System.Drawing.Bitmap
+       this    {Cytviewstuff.RegionClassification, Text: RegionClassification} Cytviewstuff.RegionClassification

These are the current values.

where is the error occuring and what is the specific error message?

The error occurs in line 6.. and the error is object reference not set to instance of object.

But I think I have stumbled across something. If you look at my previous post,
file "C:\\Users\\pashok\\Documents\\test\\image0089\\Image_2.jpg"

Look at the double slashes.. Is it because of \ being an escape sequence

no, they are double slashed because '\' is an escape sequence. In order to put a '\' in you have to escape the escape (if that makes sense). If you use a single '\' the compiler will try to escape the following character. By putting a double '\' the first tells the compiler to escape the second.

And you say the error only occurs in the last image, it applies correctly to all the other images in the folder?

actually no.. i jus checked it out.. it doesnt run even for a single image

where abouts are you using the code? I just ran a test using the same code and it loaded the images fine.

Clearly something hasnt been instantiated properly when you try to run your code. If its line 6 then my guess is that pictureBox1 doesnt exist at that point. Is your code running after InitializeComponent() and did you add pictureBox1 in the designer or in code?

It is running after InitializeComponent() and I added the pictureBox1 in the designer. I am attaching a fragment of the code here.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using AForge.Imaging;
using AForge.Imaging.ComplexFilters;
using AForge.Imaging.Filters;
using AForge.Imaging.Textures;
using System.IO;

namespace Cytviewstuff
{
    public partial class RegionClassification : Form
    {
        public RegionClassification()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog o = new OpenFileDialog();
            o.InitialDirectory = "";
            o.RestoreDirectory = true;
            if (o.ShowDialog() == DialogResult.OK)
            {
                this.pictureBox1.Image = new Bitmap(o.FileName);
                this.pictureBox1.Height = this.pictureBox1.Image.Height;
                this.pictureBox1.Width = this.pictureBox1.Image.Width;
                pictureBox1.Visible = true;
                this.Invalidate();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string[] files = Directory.GetFiles(@"C:\Users\pashok\Documents\test\image0089\","*.jpeg");
            string filename;
            int index;
            foreach (string file in files)
            {
                pictureBox1.ImageLocation = file;
                Bitmap srcImage = (Bitmap)pictureBox1.Image.Clone();
                if (srcImage.PixelFormat != PixelFormat.Format8bppIndexed)
                {
                    AForge.Imaging.Filters.Grayscale grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
                    srcImage = grayFilter.Apply(srcImage);
                }
                BitmapData srcBitmapData = srcImage.LockBits(new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height), ImageLockMode.ReadWrite, srcImage.PixelFormat);
//rest of the code(tell me if this is sufficient or u need the full code

Hmm, very odd. Firstly, does the code in button1_Click run correctly?

Next, can you try the following:
a) Insert a breakpoint at line 47. Check to see that pictureBox1 and file are not nothing at the time of executing that line.

b) run with line 47 changed to this.pictureBox1.ImageLocation = file; c) run with line 47 changed to this.pictureBox1.ImageLocation = "C:\\Users\\pashok\\Documents\\test\\image0089\\Image_2.jpg"; Let me know what they turn up :)

well, first of all, i am not using the button1_click() anymore, because i am loading the images in button2_click().

and when i changed line 47 to what u have given(both changes), I get an error in the line 54 : Parameter is not valid.

right, the reason i asked about button1 was becuase you were using this.pictureBox1. It looks like your program couldnt find 'pictureBox1' but it has found 'this.pictureBox1'.
The error at line 54 means its getting past the original problem. The new error is caused because when you set the ImageLocation it does not set the picturebox's Image property, so pictureBox1.Image = null.

Change line 47 and 48 to this:

Bitmap image;
                    using (Stream s = File.Open(file, FileMode.Open))
                    {
                        image = Bitmap.FromStream(s) as Bitmap;
                    }
                    pictureBox1.Image = image;
                    this.pictureBox1.Image = image;

This will load the file into the picturebox's Image property rather than setting the ImageLocation.
If you load the image into the picturebox directly from the file the file will be locked until your program exits, even if you subsequently change or clear the picturebox's Image property. I have loaded the image using a stream as this will avoid that problem and prevent all of your images being locked by your application.

I made the changes u mentioned, but I am now getting the error : A generic error occurred in GDI+

Trying to figure out what the problem is.. any help is welcome

you need to check your folder path i think

The folder path seems to be right, because when I tried a test application with jpg extension images n not jpeg, i got the correct output

oops, delete line 6 of my code if you havent already, meant to replace it, not duplicate it.
As for the new error, what line does it occur on? The generic error is aweful, it can relate to several issues. As avirag suggested, check the filepath and also check the permissions on the directory and files you are trying to read.

Well I had already deleted line 6 of ur code before testing.. still getting the error.. it occurs in the line 54 of my code.. and like avirag had mentioned, i checked the path, the permissions n stuff. everythn seems to be fine.. i actually changed the ImageLockMode to ReadOnly and now I am gettin an error else where..

The reason why im not adding the full code here is cause its too long.. but i can post it if u need it

I found another interesting issue.

for (int i = 0; i < pictureBox1.Height; i++)
                    {
                        for (int j = 0; j < pictureBox1.Width; j++)
                        {
                            if (srcPointer[i * pictureBox1.Width + j] != 255)
                            {
                                ++count;
                                sum += srcPointer[i * pictureBox1.Width + j];
                            }
                        }
                    }
avg = sum / count;

I now get an error in the avg=sum/count line : Divide by zero..
But the peculiar thing is when I get the error, I checked the values of avg,sum&count. The value of sum and count is 0, but the value of avg is 182.. how can that be possible ??

avg must be getting set somewhere earlier in the code.
I think this will be easier if you just upload your project and we can go through it and find the bugs for you :) It seems as though there is something systemic going on here since every time we correct one bug another pops up further down the line.

Put the project in a zip and attach it to the thread and i'll take a look for you

sure.. will do. thnx a bunch :)

ah ok im not able to upload it here.. dunno wat the prb is

i ve attached the file. can u check it out

hi,

i made another observation :

look at this code :

private void button3_Click(object sender, EventArgs e)
        {
            string[] files = System.IO.Directory.GetFiles(@"C:\Users\pashok\Documents\test\image0089\", "*.jpeg");
            Bitmap srcImage, dstImage;
            foreach (string file in files)
            {
                pictureBox1.ImageLocation = file;
                srcImage = (Bitmap)pictureBox1.Image;
                dstImage = (Bitmap)pictureBox1.Image;
                textBox1.Text = file.ToString();
            }
        }

and this :

private void button3_Click(object sender, EventArgs e)
        {
            string[] files = System.IO.Directory.GetFiles(@"C:\Users\pashok\Documents\test\image0089\", "*.jpeg");
            Bitmap srcImage, dstImage;
            foreach (string file in files)
            {
                pictureBox1.ImageLocation = file;
                srcImage = (Bitmap)pictureBox1.Image.Clone();
                dstImage = (Bitmap)pictureBox1.Image.Clone();
                textBox1.Text = file.ToString();
            }
        }

the diff is with the clone as u can see.. however i observed tat this code works fine if i do not give clone(). wen i give clone() i get this error : Object reference not set to an instance of an object.
any ideas abt this??

I'm really not sure whats going on at your end. I dont get any of the problems you are getting, but there are a lot of pointer related problems in your code. In a lot of places it is throwing AccessViolation errors, for instance in one place it is trying to read srcPointer[-202] : /

You are trying to combine several functions into a single one arent you? Did each section work correctly before you combined them?

Yeah dude, each of it worked fine.. but when im tryin to combine, i get such crappy errors

Were they each in seperate projects? Can you send me the originals? If it was all working before you combined it then obviously something has gone awry when you put the code together.

they were all in the same project - the one i sent to u.. initially I had a class called WatershedSegmentation and passed object to it from the other class. But now I have combined the whole set of operations in a single file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.