Image noise

From Rosetta Code
Revision as of 01:54, 30 September 2010 by rosettacode>Guga360 (Created page with 'Generate a random black and white image continuously, showing FPS (frames per second). =={{header|C#|C sharp}}== <lang csharp>using System; using System.Windows.Forms; using Sys…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Generate a random black and white image continuously, showing FPS (frames per second).

C#

<lang csharp>using System; using System.Windows.Forms; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Linq; using System.ComponentModel; using System.Collections.Generic;

class Program {

   static int[] colors = { 0, 255 };
   static Size size = new Size(320, 240);
   static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
   static int numbytes = size.Width * size.Height * 3;
   static PictureBox pb;
   static BackgroundWorker worker;
   static double time = 0;
   static double frames = 0;
   static Random rand = new Random();
   static IEnumerable<byte> YieldVodoo(int numpixels)
   {
       // Yield 3 times same number (i.e 255 255 255) for numpixels/3 times.
       // Numpixels is number of pixels, it's divided by 3 because it's a RGB image.
       for (int i = 0; i < numpixels / 3; i++)
       {
           var tmp = colors[rand.Next(colors.Length)];
           for (int j = 0; j < 3; j++)
           {
               yield return (byte)tmp;
           }
       }
   }
   static Image Randimg()
   {
       // Low-level bitmaps
       var bitmap = new Bitmap(size.Width, size.Height);
       var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
       var yielder = YieldVodoo(numbytes);
       Marshal.Copy(
           yielder.ToArray<byte>(), // source
           0, // start
           data.Scan0, // scan0 is a pointer to low-level bitmap data
           numbytes /* number of bytes to write*/);
       bitmap.UnlockBits(data);
       return bitmap;
   }
   static void Main()
   {
       // TODO: Fix form size.
       var form = new Form();
       form.AutoSize = true;
       form.Text = "Test";
       form.FormClosed += delegate
       {
           Application.Exit();
       };
       worker = new BackgroundWorker();
       worker.DoWork += delegate
       {
           while (true)
           {
               try
               {
                   var a = DateTime.Now;
                   pb.Image = Randimg();
                   var b = DateTime.Now;
                   time += (b - a).TotalSeconds;
                   frames += 1;
                   if (frames == 30)
                   {
                       Console.WriteLine("{0} frames in {1:0.00} seconds. ({2:0} FPS)", frames, time, frames / time);
                       time = 0;
                       frames = 0;
                   }
               }
               catch
               {
                   // Just pass.
               }                                
           }
       };
       worker.RunWorkerAsync();
       pb = new PictureBox();
       pb.Size = size;
       //pb.Dock = DockStyle.Bottom;
       form.Controls.Add(pb);
       form.Show();
       Application.Run();
   }

}</lang>

Factor

Still learning Factor, my code may suck, please fix.

<lang factor>USING: namespaces ui ui.gadgets ui.gadgets.buttons ui.gadgets.tracks ui.gadgets.borders images images.viewer models timers accessors kernel sequences sequences.deep byte-vectors random calendar io math math.functions math.parser prettyprint debugger system ; FROM: models => change-model ;

IN: imagenoise

TUPLE: imgmodel < model content ; SYMBOL: dispimg SYMBOL: num SYMBOL: ttime

randimg ( -- img )
<image>
 { 320 240 } >>dim
 RGB >>component-order
 ubyte-components >>component-type
 dup dim>> product
 [ { 255 0 } random 3 swap <repetition> ] replicate flatten >byte-vector >>bitmap ;

randimg imgmodel new-model dispimg set-global 0 num set-global 0 ttime set-global

[

 now
 dispimg get-global
 [ drop randimg ] change-model
 num get-global 1 +
 num set-global

 now swap time- duration>seconds
 ttime get-global +  
 ttime set-global
 
 num get-global 10 <= 
  [ ]
  [
   num get-global 
   ttime get-global 
   [ / round number>string " FPS" append ] try print
   0 num set-global
   0 ttime set-global ] if  

] 1 nanoseconds every

[ vertical <track>

dispimg get-global <image-control> { 5 5 } <border> f track-add  
 
"Test" open-window

] with-ui</lang>

Python

Using Tkinter and PIL.

<lang python>import Tkinter import Image, ImageTk import random import time

colors = [(0,0,0),(255,255,255)] size = (320,240) pixels = size[0] * size[1]

class App():

   def __init__(self, root):  
       self.root = root
       self.root.title("Test")
       
       self.img = Image.new("RGB",size)        
       self.label = Tkinter.Label(root)
       self.label.pack()
       self.time = 0.0
       self.frames = 0        
       self.loop() 
   def loop(self):
       self.ta = time.time()        
       self.img.putdata([random.choice(colors) for i in range(pixels)])
       self.pimg = ImageTk.PhotoImage(self.img)
       self.label["image"] = self.pimg        
       self.tb = time.time()
       
       self.time += (self.tb - self.ta)
       self.frames += 1
       if self.frames == 30:
           try:
               self.fps = self.frames / self.time
           except:
               self.fps = "INSTANT"
           print "%d frames in %3.2f seconds (%s FPS)" % (self.frames, self.time, self.fps)
           self.time = 0
           self.frames = 0
     
       self.root.after(1, self.loop)

root = Tkinter.Tk() app = App(root) root.mainloop()</lang>