Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion, Adobe Flex

ColdFusion: Article

How To Use ColdFusion to Search Images Based on Color

A starting point

This article describes a basic method for indexing and searching images and digital photographs based on color using ColdFusion and CFImageHistogram (www.leavethatthingalone.com/projects/cfhistogram/). This method indexes and searches color in images quickly using ColdFusion.

I don't pretend to claim that this is the best way to search images based on color as there are other more in-depth and precise methods. For more information I suggest you read more about content-based image retrieval systems (http://en.wikipedia.org/wiki/Content-based_image_retrieval).

Note: The code examples below range from pseudo-code to 95% of what you will need to index and search images. There are so many possibilities of how images and image color information can be stored that it's hard to demonstrate a one-size-fits-all solution.

Where to Start
To be able to search for colors in an image we have to know something about the colors that make up that image. A histogram is a good way to do this. More important, a color histogram is useful because it tracks the frequency of colors that occur in an image. Each occurrence of a color, in this case red-green-blue, is counted based on its value 0-255.

To get the color histogram of an image, you need to inspect each pixel and calculate the red/green/blue components of that pixel. This can be a very slow process, so it may be best to resize a large image before trying to calculate the color histogram.

Some Statistics
The CFImageHistogram (www.leavethatthingalone.com/projects/cfhistogram/) color histogram creates an array for each of the three colors (R-G-B). In each array there are 255 cells that store the count of the occurrences of that particular color (0-255). While the arrays are nice to have, it's more important to be able to search knowing the mean and standard deviation of that color's array. The mean will tell us what the average color is and the standard deviation will give us an idea of how spread out the color range might be.

Color Information
This statistical color information works well. We can take an image and find the average red, green, and blue for it, then store this information in a database and query for images that have a high occurrence of blue, for example. But the problem is that most images have a mix of colors, so when you retrieve the color histogram of the entire image, you get an average result that tends to be the average color for the entire image and that's most likely some grayish color (see Figure 1).

A solution to this is to split the image into sub-images. By looking at the color histogram information and the mean/standard deviation of smaller regions of the image, we can better search within that image. By looking in smaller areas of the image we're more likely to get average colors for the histogram that better reflect the colors in the image (see Figure 2).

The more sub-images (or bins) that you use, the more accurate your searches can be; however, there is a trade off in the processing time it takes to index the images and then later the search query time.

Indexing the Images
The code examples below might be a little unclear, so I've included a basic flow chart that should help in understanding the process of indexing the color information on the images (see Figure 3). This image is also available at www.leavethatthingalone.com/examples/cfcolorsearch/img/cfflowchart.png.

The first step to getting this color information out of an image is to buffer an image so we can manipulate it:

<cfscript>
//image to get color information from
photo = expandPath("photo.jpg");
//Jpeg Codec
jpegCodec = createObject("java", "com.sun.image.codec.jpeg.JPEGCodec");
//file input
fileInputStream = createObject("java", "java.io.FileInputStream").init(photo);
//decodes the JPEG
decoder = jpegCodec.createJPEGDecoder(fileInputStream);
//get buffered image
bufferedImage = decoder.decodeAsBufferedImage();
imageHeight = bufferedImage.getHeight();//buffered image height
imageWidth = bufferedImage.getWidth();//buffered image width
</cfscript>

Now that we have a buffered image, we need to be able to isolate the subimages within the image. The "subImage" method of the bufferedImage can be used. The subImage creates a new buffered image based on a rectangle defined in the arguments:

subImage = bufferedImage.getSubimage(x,y,width,height);

Once we have an isolated region of an image, we need to get the color histogram and color statistics of it. This can be done with the CFImageHistogram:

<cfscript>
//create image histogram object
imageHistogram = createObject("component","imageHistogram").init();
//set the buffered subimage into the image histogram object
imageHistogram.setBufferedImage(subImage);
//get the color histogram and color statictics struct
hist = imageHistogram.getColorHistogram();
</cfscript>

We need to store this image color histogram information in a database table so that we can query it. We'll also need to store a unique ID of the image (either a file name or database ID) and the means and standard deviations. CFImageHistogram will return a struct containing the histogram and color statistics for the R-G-B of the image. Here is an example of what that query might look Listing 1.

While looping through each of the 16 sub-images, we need to store this information based on a unique ID or the filename of this image so we can later query this data. Putting the above code snippets together we can index images. Listing 2 provides a more in-depth example of how to index a database or cfdirectory of images, storing color data for each sub-image within each image.

This process of storing the data of each sub-image needs to be repeated for all the images you would like to search. You can do this within a cfoutput of a cfdirectory or a query result of image locations. This process can be very slow; each image may take as long as 1-5 seconds to process depending on the size of the original image, the size and number of sub-images, and your server's speed. This can also create a large number of records, for example, 200 images at 16 bins per image = 3200 records.

Searching the Indexed Images
Once we have a database table populated with image region color information, we need to figure out how to search for a color. We'll do this based on a single color and look for images that have the most occurrences (or nearest) in their sub areas. We'll query the database looking for rows that are closest to the R-G-B color selected. We'll use a SQL "between".

That query will return all the matches of the colors that fall in those ranges, which is fine but we'd like to know which images have the most occurrences. We will add some grouping and sorting to the query so that we return, in order, the images that have the highest occurrence of the color selected (see Listing 3). Chances are fairly high that most selected colors won't return any exact matches to the selected color, so you may need to add more range that the record's color mean can fall into. You may even want to loop the query several times, each time expanding the range until you have, say, 10 results.

To view a demo color search (see Figure 4) go to: www.leavethatthingalone.com/examples/cfcolorsearch/index.cfm.

Final Notes
This page article is meant as a starting point. There is much more that could be done and/or improved with this method. The search query could definitely be improved to better take into account the standard deviation of sub-images. Also since we are storing colors in areas of an image, it would be possible to search images based on patterns or drawings similar to the way retrievr (http://labs.systemone.at/retrievr/) works.

More Stories By Seth Duffey

Seth Duffey is the webmaster for the City of Davis, California. He is also the manager of the Sacramento ColdFusion Users Group. His blog is http://www.leavethatthingalone.com.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Announcing Poland #DigitalTransformation Pavilion
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
CloudEXPO | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
In past @ThingsExpo presentations, Joseph di Paolantonio has explored how various Internet of Things (IoT) and data management and analytics (DMA) solution spaces will come together as sensor analytics ecosystems. This year, in his session at @ThingsExpo, Joseph di Paolantonio from DataArchon, added the numerous Transportation areas, from autonomous vehicles to “Uber for containers.” While IoT data in any one area of Transportation will have a huge impact in that area, combining sensor analytic...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
I think DevOps is now a rambunctious teenager - it's starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.