Posts Tagged ‘image’

mixed fem google images search

Sunday, July 18th, 2010

I was mindlessly searching on google for “mixed fem”, as in “Mixed Finite Elements Method”, and when I switched to searching images I was surprised by the results:
screen shot of searching mixed fem on google images
Textbook covers, heat maps, marijuana and semi-nude wrestling. See for yourself!

Make your own single image iPhone apps

Monday, July 12th, 2010

I’ve now made it possible for you to make your very own single image iPhone apps. Just enter in the url of the app’s image and I will take care of the html mumbo jumbo and icon. I’m not going to host the images, but I will provide a URL for your app. It is of course free, and there are lots of websites that do free image hosting.

Your apps will work offline, too, as long as your user’s know to save them to their iPhone/iPod/iPad home screen. The caching system I set up when you click “upload” does the rest.

Batch convert eps files to svg using pstoedit

Tuesday, December 8th, 2009

My student mac version of MATLAB won’t print to svg so I’m stuck with a bunch of eps files. I needed a way to batch convert all my MATLAB plots to svg.

First step: get pstoedit, on a mac I just issue:


sudo port install pstoedit

On linux you can probably do


sudo apt-get install pstoedit

Then in a bash terminal using the same idea as an earlier post you can issue:


for filename in *.eps; \
do newname=`echo $filename | sed 's/\.eps$/.svg/g'`; \
pstoedit -f plot-svg $filename $newname; \
done

Vi(m) tip #5: convert list of image files into latex figures

Wednesday, November 11th, 2009

If I select and copy (CMD+C) a bunch of image files in Finder
then paste (CMD+V) in TextEdit, then recopy and paste into vi(m), I can run the follow commands to make each file into a full blown latex figure. (Of course you can also just copy and paste the list using ls on any unix/linux machine.)

For eps files:


:%s/^\(.*eps\)$/\r\\begin{figure}[tbp]\r\\centering\r\\epsfig{file=\1,width=0.9\\linewidth,clip=}\r\\caption{}\r\\end{figure}/

and for others (png here, just replace with jpg etc.):


:%s/^\(.*png\)$/\r\\begin{figure}[tbp]\r\\centering\r\\includegraphics[width=0.9\\textwidth]{\1}\r\\caption{}\r\\end{figure}/

Example:

The first one-liner substitutes:


bilapl_all_bnds_ex.eps
bilapl_all_bnds_ey.eps
trilapl_all_bnds_ex.eps
trilapl_all_bnds_ey.eps
trilapl_all_bnds_ez.eps

with this:


\begin{figure}[tbp]
\centering
\epsfig{file=bilapl_all_bnds_ex.eps,width=0.9\linewidth,clip=}
\caption{}
\end{figure}

\begin{figure}[tbp]
\centering
\epsfig{file=bilapl_all_bnds_ey.eps,width=0.9\linewidth,clip=}
\caption{}
\end{figure}

\begin{figure}[tbp]
\centering
\epsfig{file=trilapl_all_bnds_ex.eps,width=0.9\linewidth,clip=}
\caption{}
\end{figure}

\begin{figure}[tbp]
\centering
\epsfig{file=trilapl_all_bnds_ey.eps,width=0.9\linewidth,clip=}
\caption{}
\end{figure}

\begin{figure}[tbp]
\centering
\epsfig{file=trilapl_all_bnds_ez.eps,width=0.9\linewidth,clip=}
\caption{}
\end{figure}

Google images game: high score

Monday, October 26th, 2009

I will try to implement a current high score or high scores feature to the Google images game, but in the mean time I will post screenshots here. Here’s the first known “Hard” solution found for the “Nouns” game:


Google images game first hard solution


Try to beat this score!

Leave a comment below or contact me with a screen shot of your high score.

Google images game

Sunday, October 25th, 2009


google images game screen shot

I finished coding a rather simple but addictive and challenging puzzle game, I’m calling the Google images game. The player is presented with the image results of a Google images search for some search word or phrase. The player’s objective is to guess and figure out what that search phrase was. Play it now!

The game is an amalgamation of php, javascript and ruby. The ajax javascript for the game is rather complicated by now to handle all of the gaming options, but it’s all visible in the game’s page source. I use a little ruby program to grab the initial google images thumbnails:


#!/usr/bin/ruby
require 'uri'
require 'net/http'
require 'cgi'

SAFE_VALUES = ["on","moderate","off"]
cgi = CGI.new("html3")
safe = "moderate"
safe = cgi["safe"] if(!cgi["safe"].empty? and SAFE_VALUES.include?(cgi["safe"]))
target = ""
target = cgi["target"] if(!cgi["target"].empty?)

if(!cgi["query"].empty?)
  address = "http://images.google.com/images?q="+
    cgi["query"].gsub(/ /,"+")+"&safe="+safe
  uri = URI(address)
  http = Net::HTTP.new(uri.host, uri.port)
  headers = {
    "User-Agent" => "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)"
    }

  code = http.head(address, headers).code.to_i
  if (code >= 200 && code < 300) then

      #the data is available...
      response = ""
      http.get(address, headers) do |chunk|
        response = response + chunk
      end
      images = []
      response.scan(
        /imgurl=(.+?)&imgrefurl=(.+?)&[^<]+<img src=(.+?) /
        ) do |img, ref, thumb|
        images<<[img,ref, thumb]
      end
      images.collect! do |e|
        "<a title='"+e[1]+" 'href='"+
        CGI.unescape(e[1]).gsub(/'/,"%27").gsub(/ /,"%20")+
        "' target='"+target+"'><img src='"+e[2]+"' height='100px'></a>"
      end
      cgi.out{
        images.join(" ")
      }
  end
end

I use a little php program to return a random line (initial search phrase/word) from a given file:


  $difficulty = 'easy';
  if (isset($_GET['difficulty'])&&strlen($_GET['difficulty'])>0) {
      $difficulty= $_GET['difficulty'];
  }
  $word_list = 'nouns.txt';
  $possible_word_lists = array('nouns.txt','wiki.txt');
  if (isset($_GET['word_list'])&&strlen($_GET['word_list'])>0) {
      if(in_array($_GET['word_list'],$possible_word_lists)){
        $word_list = $_GET['word_list'];
      }
  }

  $query = "";
  $word_count = 1;
  if(strcmp($word_list,'nouns.txt')==0){
    if(strcmp($difficulty,"medium")==0){
      $word_count = 2;
    }else if(strcmp($difficulty,"hard")==0){
      $word_count = 3;
    }
  }
  for($i=0; $i<$word_count; $i=$i+1){
    if(strlen($query)>0){
      $query= $query."+";
    }
    $query = $query.`ruby -e "a=File.readlines('$word_list').collect{|line| line.strip.gsub(' ','+').gsub('\'','%27')};puts a[rand*a.leng
    $query = trim($query);
  }
  print trim($query);

As you can see, I gave up on php half way through and cheated by calling a ruby one-liner. Someday I'll fix this up...

Resize image pixel by pixel without antialiasing (raw scale)

Monday, October 12th, 2009

Using image magick’s convert util, you can resize an image without any blurring or fuzziness by issuing the command with these options (this particularly resizes height to 1920 pixels):


convert input.png -filter Point -resize x1920 +antialias output.png

I resized this:

before resize

to


before resize

Convert image file to html page using div blocks

Monday, October 12th, 2009

This is the revival of an old program I was requested to make. Given any .png, .jpg, .jpeg, .bmp, image file, DivMachine converts that image into a collection of colored divs. So given this image (8 KB):

div machine input image

DivMachine produces (164 KB):


<style type="text/css">
div.dm {
  position:absolute;
}
</style>
<div style="position: relative;padding:20px;background-color:#c3e0f0;width:100px;height:126px;">
<div class='dm' style="top:0px; left:58px; background-color:#2F2F31; width:1px; height:1px"></div>
<div class='dm' style="top:0px; left:56px; background-color:#2D2720; width:2px; height:2px"></div>
<div class='dm' style="top:1px; left:58px; background-color:#251C13; width:1px; height:1px"></div>
<div class='dm' style="top:0px; left:59px; background-color:#26292D; width:1px; height:2px"></div>
<div class='dm' style="top:2px; left:57px; background-color:#513E21; width:3px; height:1px"></div>
<div class='dm' style="top:0px; left:60px; background-color:#25292C; width:1px; height:3px"></div>
...

which displayed as html looks like this:

The source is included in the zip file.

Pad images to fit 4 by 6 photo paper bash script using imagemagick

Sunday, August 16th, 2009

I was a little dismayed that I couldn’t use my previously mentioned applescript to pad images with colors other than black. A shrewd observer will also notice that the Image Events suite resamples when it pads resulting in some annoying re-anti-aliasing.

I wrote the following bash script to the same task as the applescript from the command line:


#!/bin/bash

USAGE="Usage: $0 [--replace] [--padcolor=color] ratio imagefile(s)
  ratio              is a float equal to long dimension / short dimension to pad
                     to fit a 4\"x6\" card, divide 6 by 4 giving ratio = 1.5
  --replace or -f    option to overwrite original images with padded versions,
                     default is to preppend 'pad-[ratio]-' to each naee
  --padcolor= or -c= option to change pad color from default black. Takes a
                     color can be any Imagemagick color or hex color:
                     (See http://www.imagemagick.org/script/color.php)
"
if [ "$#" == "0" ]; then
  echo "$USAGE"
  exit 1
fi

replace=false
if [ "$1" == "--replace" -o "$1" == "-f" ]
then
  echo "Overwriting existing image files..."
  replace=true
  shift
fi

padcolor="black"
if [ `echo "$1" | grep "^\(--padcolor\)\|\(-c\)="` ]
then
  padcolor=`echo "$1" | sed "s/^.*=//"`
  shift
  echo "Using $padcolor as pad color..."
fi

ratio=`echo "$1" | grep "^[0-9]*\.\?[0-9]\+$\|^[0-9]\+\.$"`
if [ "$ratio" == "" ]
then
  echo "$USAGE"
  exit 2
fi
shift
while (( "$#" )); do
  image="$1"
  dir=`dirname "$image"`
  base=`basename "$image"`
  if ! $replace
  then
    base="pad-$ratio-$base"
  fi
  if wh=`identify -format "%w %h" "$image" 2>/dev/null`
  then
    width=${wh%% *}
    height=${wh#* }
    if [ $height -gt $width ]
    then
      # vertical
      long=`echo "$height/$width > $ratio" | bc -l`
      if [ $long -eq "1" ]
      then
        # taller than ratio
        newwidth=`echo "$height/$ratio" | bc -l`
        newwidth=`echo "($newwidth+0.5)/1" | bc`
        newheight="$height"
      else
        # shorter than ratio
        newwidth="$width"
        newheight=`echo "$width*$ratio" | bc -l`
        newheight=`echo "($newheight+0.5)/1" | bc`
      fi
    else
      # horizontal
      long=`echo "$width/$height > $ratio" | bc -l`
      if [ $long -eq "1" ]
      then
        # wider than ratio
        newwidth="$width"
        newheight=`echo "$width/$ratio" | bc -l`
        newheight=`echo "($newheight+0.5)/1" | bc`
      else
        # skinnier than ratio
        newwidth=`echo "$height*$ratio" | bc -l`
        newwidth=`echo "($newwidth+0.5)/1" | bc`
        newheight="$height"
      fi
    fi
    printf "Padding into $base..."
    convert -size "$newwidth"x"$newheight" xc:"$padcolor" .padcanvas.miff
    composite -gravity center "$image" .padcanvas.miff "$dir"/"$base"
    rm .padcanvas.miff
    echo "DONE"
  else
    echo "$image is not a proper image...skipping."
  fi
  shift
done

I have not completely bullet proofed the above but it should get the job done.

Here’s the same before and after shots to show what this script does:

Original Padded with black Padded with transparent pixels
Long horizontal before Long horizontal after Long horizontal after
Short horizontal before Short horizontal after Short horizontal after
Long vertical after Long vertical after Long vertical after
Short vertical before Short vertical after Short vertical after

Look closely at the last column, the images are padded with transparent pixels! Could be useful for web posting.

Pad images to fit 4 by 6 photo paper using applescript

Sunday, August 16th, 2009

I recently got my 4″ by 6″ prints from an online photo printing site. Most of the images had been arbitrarily cropped to fit the paper. I wrote an applescript to pad images to fit on a 4″ by 6″ print, so that the site wouldn’t need to adjust my images. The script doesn’t change the size of the image to 4″ by 6″, it just pads the image in one direction to fit a 4 by 6 or 6 by 4 ratio, whichever requires the least padding.


on open (listOfFiles)
	set replace to button returned of (display dialog "Replace existing files?" buttons {"Yes", "No"})
	repeat with this_file in listOfFiles
		set the new_file_name to (this_file as string)
		if replace = "No" then
			set parsed_path to my parse_file(this_file)
			set full_name to item 2 of parsed_path & "." & item 3 of parsed_path
			set input_name to ""
			repeat while input_name = ""
				set input_name to text returned of (display dialog "Save padded version of " & full_name & " as:" default answer full_name)
			end repeat
			if input_name does not end with item 3 of parsed_path then
				set input_name to input_name & item 3 of parsed_path
			end if
			set new_file_name to item 1 of parsed_path & ":" & input_name
		end if
		try
			tell application "Image Events"
				launch
				set this_image to open (this_file as string)

				set this_list to dimensions of this_image
				set width to (item 1 of this_list as integer)
				set height to (item 2 of this_list as integer)

				-- rotate to simplify things
				if height is greater than width then
					if height / width > (6.0 / 4.0) then
						pad this_image to dimensions {height * (4.0 / 6.0), height} --with pad color {255,255,255}
					else
						pad this_image to dimensions {width, width * (6.0 / 4.0)} --with pad color {255,255,255}
					end if
				else
					if width / height > (6.0 / 4.0) then
						pad this_image to dimensions {width, (width / (6.0 / 4.0))} --with pad color {255,255,255}
					else
						pad this_image to dimensions {(6.0 / 4.0) * height, height} --with pad color {255,255,255}
						-- not wide enough
					end if
				end if

				save this_image in new_file_name with icon
				close this_image
			end tell
		on error error_message
			display dialog error_message
		end try

	end repeat
	quit application "Image Events"
end open

-- given a file (or folder) return a list containing
--   the path to its parent directory,
--   its name without its file extension, and
--   its file extension
on parse_file(this_file)
	set default_delimiters to AppleScript's text item delimiters
	-- if given file is a folder then strip terminal ":" so as to return
	-- folder name as file name and true parent directory
	if last item of (this_file as string) = ":" then
		set AppleScript's text item delimiters to ""
		set this_file to (items 1 through -2 of (this_file as string)) as string
	end if
	set AppleScript's text item delimiters to ":"
	set this_parent_dir to (text items 1 through -2 of (this_file as string)) as string
	set this_name to (text item -1 of (this_file as string)) as string
	-- default or no extension is empty string
	set this_extension to ""
	if this_name contains "." then
		set AppleScript's text item delimiters to "."
		set this_extension to the last text item of this_name
		set this_name to (text items 1 through -2 of this_name) as string
	end if
	set AppleScript's text item delimiters to default_delimiters
	return {this_parent_dir, this_name, this_extension}
end parse_file

Save this in a script and then drag some images onto the script.

Here’s some before and after shots to show what this script does:

Original Padded
Long horizontal before Long horizontal after
Short horizontal before Short horizontal after
Long vertical before Long vertical after
Short vertical before Short vertical after

Note: If you are running Mac OS X 10.5 then you can uncomment the with pad color {255,255,255} lines to change the padding color from the default black to white or any other color.
Note: I’m using my (hopefully) bulletproof file path parse function, parse_file, which I have recently posted about.