Image noise: Difference between revisions

m
m (syntax highlighting fixup automation)
 
(12 intermediate revisions by 8 users not shown)
Line 694:
 
=={{header|C++}}==
===Version 1 (windows.h)===
[[File:noise_cpp.png]]
<syntaxhighlight lang="cpp">
Line 928 ⟶ 929:
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
 
===Version 2 (SDL2)===
{{libheader|SDL2}}
'''Source:''' https://gist.github.com/KatsumiKougen/58c53e77dc45e4e3a13661ff7b38c1ea
<syntaxhighlight lang="cpp">
// Standard C++ stuff
#include <iostream>
#include <string>
#include <random>
 
// SDL2 stuff
#include "SDL2/SDL.h"
 
// Other crazy stuffs
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 240
#define COLOUR_BLACK 0, 0, 0, 0xff
#define COLOUR_WHITE 0xff, 0xff, 0xff, 0xff
 
// Compile: g++ -std=c++20 -Wall -Wextra -pedantic ImageNoise.cpp -o ImageNoise -lSDL2
 
template <class RandomGenerator>
void BlitNoise(SDL_Renderer *r, int width, int height, auto &dist, RandomGenerator &generator) {
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
// Use the random number generator in C++ Standard Library to determine draw colour
if (dist(generator) == 0)
// Set colour to black
SDL_SetRenderDrawColor(r, COLOUR_BLACK);
else if (dist(generator) == 1)
// Set colour to white
SDL_SetRenderDrawColor(r, COLOUR_WHITE);
// Go through every scanline, and put pixels
SDL_RenderDrawPoint(r, x, y);
}
}
}
 
void UpdateFPS(unsigned &frame_count, unsigned &timer, SDL_Window *window) {
static Uint64 LastTime = 0;
std::string NewWindowTitle;
Uint64 Time = SDL_GetTicks(),
Delta = Time - LastTime;
timer += Delta;
if (timer > 1000) {
unsigned ElapsedTime = timer / 1000;
NewWindowTitle = "Image noise - " + std::to_string((int)((float)frame_count/(float)ElapsedTime)) + " FPS"; // Dirty string trick
SDL_SetWindowTitle(window, const_cast<char*>(NewWindowTitle.c_str()));
timer = 0;
frame_count = 0;
NewWindowTitle.clear();
}
LastTime = Time;
}
 
int main() {
std::random_device Device; // Random number device
std::mt19937_64 Generator(Device()); // Random number generator
std::uniform_int_distribution ColourState(0, 1); // Colour state
unsigned Frames = 0,
Timer = 0;
SDL_Window *Window = NULL; // Define window
SDL_Renderer *Renderer = NULL; // Define renderer
// Init everything just for sure
SDL_Init(SDL_INIT_EVERYTHING);
// Set window size to 320x240, always shown
Window = SDL_CreateWindow("Image noise - ?? FPS", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
Renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED);
// Set background colour to white
SDL_SetRenderDrawColor(Renderer, COLOUR_WHITE);
SDL_RenderClear(Renderer);
// Create an event handler and a "quit" flag
SDL_Event e;
bool KillWindow = false;
// The window runs until the "quit" flag is set to true
while (!KillWindow) {
while (SDL_PollEvent(&e) != 0) {
// Go through the events in the queue
switch (e.type) {
// Event: user hits a key
case SDL_QUIT: case SDL_KEYDOWN:
// Destroy window
KillWindow = true;
break;
}
}
// Render the noise
BlitNoise(Renderer, SCREEN_WIDTH, SCREEN_HEIGHT, ColourState, Generator);
SDL_RenderPresent(Renderer);
// Increment the "Frames" variable.
// Then show the FPS count in the window title.
++Frames;
UpdateFPS(Frames, Timer, Window);
}
// Destroy renderer and window
SDL_DestroyRenderer(Renderer);
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
</syntaxhighlight>
 
{{output}}
<center>[[File:C++ image noise SDL2.gif|280px]]</center>
 
=={{header|Common Lisp}}==
Line 1,105 ⟶ 1,218:
1400 to 1600 FPS
</pre>
=={{header|EasyLang}}==
[https://easylang.dev/show/#cod=XZDBqoMwEEX3fsWhi0dLaRp1UbPw/Yi4kDSCUI3EUPTvH9EE+roImTl3Zm4ys7OaeTGelQ2NQGSAti/r0CEc7duwcqcUBdtxB+6M9khRhpOJzE500zB23gSxd1xr8hAOPcu2+GE03PCS38jT6FzyqCI4bG9FTHeLSlLI//p3f5V0b1YfvO+cPz0v/HCin5dTqpPU6VUR9Y6afU5aQNNS0yClRClFu//LOtZQiLeUuUrN1rElnKuE4WO19tW4bnoOk6doY4E4/ET2Bw== Run it]
 
<syntaxhighlight>
proc pset x y c . .
color c
move x / 3.2 y / 3.2
rect 0.3 0.3
.
on animate
fr += 1
if systime - t0 >= 1
move 10 78
color -2
rect 80 20
color -1
move 10 80
text fr / (systime - t0) & " fps"
t0 = systime
fr = 0
.
col[] = [ 000 999 ]
for x = 0 to 319
for y = 0 to 199
pset x y col[randint 2]
.
.
.
</syntaxhighlight>
 
=={{header|Euler Math Toolbox}}==
 
Line 1,276 ⟶ 1,419:
{ { title "Black and White noise" } }
<bw-noise-gadget> with-fps >>gadgets ;</syntaxhighlight>
 
 
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
{{libheader|SDL2}}
 
<syntaxhighlight lang="Forth">\ Bindings to SDL2 functions
s" SDL2" add-lib
\c #include <SDL2/SDL.h>
c-function sdl-init SDL_Init n -- n
c-function sdl-quit SDL_Quit -- void
c-function sdl-createwindow SDL_CreateWindow a n n n n n -- a
c-function sdl-createrenderer SDL_CreateRenderer a n n -- a
c-function sdl-setdrawcolor SDL_SetRenderDrawColor a n n n n -- n
c-function sdl-drawpoint SDL_RenderDrawPoint a n n -- n
c-function sdl-renderpresent SDL_RenderPresent a -- void
c-function sdl-delay SDL_Delay n -- void
c-function sdl-ticks SDL_GetTicks -- n
 
require random.fs
 
0 value window
0 value renderer
240 constant height
320 constant width
 
: black 0 0 0 255 ;
: white 255 255 255 255 ;
: black-or-white 2 random if black else white then ;
 
: init-image ( -- )
$20 sdl-init drop
s\" Rosetta Task : Image Noise\x0" drop 0 0 width height $0 sdl-createwindow to window
window -1 $2 sdl-createrenderer to renderer
page
;
 
: image-noise-generate
height 0 do
width 0 do
renderer black-or-white sdl-setdrawcolor drop
renderer i j sdl-drawpoint drop
loop
loop
;
 
: .FPS swap - 1000 swap / 0 0 at-xy . ." FPS" ;
 
: image-noise
init-image
100 0 do
sdl-ticks
image-noise-generate renderer sdl-renderpresent
sdl-ticks .FPS
loop
sdl-quit
;
 
image-noise</syntaxhighlight>
 
 
 
 
=={{header|FreeBASIC}}==
Line 1,314 ⟶ 1,519:
 
Wend</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
FB has native image noise filters.
<syntaxhighlight lang="futurebasic">
 
_window = 1
begin enum output 1
_noiseView
_fpsLabel
end enum
 
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 340, 300 )
window _window, @"Rosetta Code Image Noise", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
r = fn CGRectMake( 10, 50, 320, 240 )
imageview _noiseView, YES, , r, NSImageScaleAxesIndependently, NSImageAlignCenter, NSImageFrameNone, _window
r = fn CGRectMake( 20, 10, 280, 24 )
textlabel _fpsLabel, @"Estimated FPS: 60", r, _window
ControlSetAlignment( _fpsLabel, NSTextAlignmentCenter )
end fn
 
local fn CIImageToImageRef( ciImage as CIImageRef ) as ImageRef
CIImageRepRef rep = fn CIImageRepWithCIImage( ciImage )
CGSize size = fn ImageRepSize( rep )
ImageRef image = fn ImageWithSize( size )
ImageAddRepresentation( image, rep )
end fn = image
 
local fn NoiseCIImage as CIImageRef
CIFilterRef filter = fn CIFilterWithName( @"CIPhotoEffectNoir" )
ObjectSetValueForKey( filter, fn ObjectValueForKey( fn CIFilterWithName(@"CIRandomGenerator"), @"outputImage" ), @"inputImage" )
CIFilterSetDefaults( filter )
CIImageRef outputCIImage = fn CIImageByCroppingToRect( fn CIFilterOutputImage( filter ), fn CGRectMake( rnd(1000), rnd(1000), 500, 500 ) )
end fn = outputCIImage
 
local fn BuildNoiseView
block NSInteger renderedFrames
renderedFrames = 0
timerbegin, 1.0/60, YES
CIImageRef noiseCIImage = fn NoiseCIImage
ImageRef noiseImage = fn CIImageToImageRef( noiseCIImage )
ImageViewSetImage( _noiseView, noiseImage )
renderedFrames++
if( renderedFrames == 60 )
ControlSetStringValue( _fpsLabel, fn StringWithFormat( @"Estimated FPS: %ld", renderedFrames ) )
renderedFrames = 0
end if
timerend
end fn
 
void local fn DoDialog( ev as long, tag as long, wnd as long )
select ( ev )
case _windowWillClose : end
end select
end fn
 
 
randomize
 
on dialog fn DoDialog
 
fn BuildWindow
fn BuildNoiseView
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Image Noise.png]]
 
 
=={{header|Go}}==
Line 2,157 ⟶ 2,436:
createdialog testrollout
</syntaxhighlight>
 
=={{header|MiniScript}}==
This implementation is for use with [http://miniscript.org/MiniMicro Mini Micro].
<syntaxhighlight lang="miniscript">
clear
tileSetLength = 32
width = 320
height = 240
cellSize = [960/width, 600/height]
colors = [color.black, color.white]
 
newImg = function
img = Image.create(tileSetLength, 1)
for i in range(0, tileSetLength - 1)
img.setPixel i, 0, colors[rnd * 2]
end for
return img
end function
 
display(5).mode = displayMode.tile
td = display(5)
td.cellSize = cellSize
td.extent = [width, height]
td.tileSetTileSize = 1
for x in range(0, width - 1)
for y in range(0, height - 1)
td.setCell x, y, rnd * tileSetLength
end for
end for
frames = 0
startTime = time
while true
td.tileSet = newImg
frames += 1
dt = time - startTime
if dt >= 1 then
text.row = 25; print "FPS: " + round(frames / dt, 2)
frames = 0
startTime = time
end if
end while
</syntaxhighlight>
[[File:Minimicro-noise-32.gif]]
 
=={{header|Nim}}==
Line 2,736 ⟶ 3,058:
<syntaxhighlight lang="python">import time
import random
import Tkintertkinter
from PIL import Image, ImageTk # PIL libray
from PIL import ImageTk
 
 
class App(object):
class App:
def __init__(self, size, root):
self.root = root
self.root.title("Image Noise Test")
 
self.img = Image.new("RGB1", size)
self.label = Tkintertkinter.Label(root)
self.label.pack()
 
Line 2,751 ⟶ 3,075:
self.frames = 0
self.size = size
self.n_pixels = self.size[0] * self.size[1]
 
self.loop()
 
def loop(self):
self.tastart_time = time.time()
# 13 FPS boost. half integer idea from C#.
rnd = random.random
white = (255, 255, 255)
black = (0, 0, 0)
npixels = self.size[0] * self.size[1]
data = [white if rnd() > 0.5 else black for i in xrange(npixels)]
self.img.putdata(data)
self.pimg = ImageTk.PhotoImage(self.img)
self.label["image"] = self.pimg
self.tb = time.time()
 
self.time += img.putdata(self.tb - self.ta)
[255 if b > 127 else 0 for b in random.randbytes(self.n_pixels)]
)
 
self.bitmap_image = ImageTk.BitmapImage(self.img)
self.label["image"] = self.bitmap_image
 
end_time = time.time()
self.time += end_time - start_time
self.frames += 1
 
if self.frames == 30:
try:
self.fps = self.frames / self.time
except ZeroDivisionError:
self.fps = "INSTANT"
 
print ("%d frames in %3.2f seconds (%s FPS)" %
print(f"{self.frames,} frames in {self.time,:3.2f} self.seconds ({fps} FPS)")
self.time = 0
self.frames = 0
 
self.root.after(1, self.loop)
 
 
def main():
root = Tkintertkinter.Tk()
app = App((320, 240), root)
root.mainloop()
 
 
main()</syntaxhighlight>
if __name__ == "__main__":
About 28 FPS max, Python 2.6.6.
main()
</syntaxhighlight>
 
=={{header|Racket}}==
Line 2,924 ⟶ 3,251:
end /*y*/ /* [↑] build the image. */
return</syntaxhighlight>
 
=={{header|RPL}}==
RPL can only handle 131x64 screens. Despite such a small size, displaying graphics is very slow: FPH (frames Per Hour) would be a more appropriate unit.
====HP 28/48 version====
≪ TICKS (0,0) PMIN (130,64) PMAX
'''DO'''
CLLCD
'''IF''' TICKS OVER - 8192 / B→R '''THEN'''
LAST INV 3 DISP '''END'''
0 130 '''FOR''' x
0 63 '''FOR''' y
'''IF''' RAND 0.5 > '''THEN''' x y R→C PIXEL '''END'''
'''NEXT NEXT'''
'''UNTIL''' 0 '''END'''
≫ '<span style="color:blue">NOISE</span>' STO
HP-28 users shall replace <code>TICKS</code> by a <code>SYSEVAL</code> call, which address value depends on their ROM version.
====HP-48G version====
From the HP-48G model, the graphics system has been completely reviewed, and so the commands:
≪ TICKS
'''DO'''
ERASE
'''IF''' TICKS OVER - 8192 / B→R '''THEN'''
LASTARG INV 1 →GROB PICT RCL {#0h #42h} ROT GOR PICT STO {#0 #0} PVIEW '''END'''
0 130 '''FOR''' x
0 63 '''FOR''' y
'''IF''' RAND 0.5 > '''THEN''' x R→B y R→B 2 →LIST PIXON '''END'''
'''NEXT NEXT'''
{#0 #0} PVIEW
'''UNTIL''' 0 '''END'''
≫ '<span style="color:blue">NOISE</span>' STO
FPS = 0.0095
 
=={{header|Ruby}}==
Line 3,237 ⟶ 3,595:
=={{header|Wren}}==
{{libheader|DOME}}
<syntaxhighlight lang="ecmascriptwren">import "dome" for Window
import "graphics" for Canvas, Color
import "random" for Random
2,069

edits