Pixelsorting in PureBasic

Developed or developing a new product in PureBasic? Tell the world about it.
knut_the_dude
New User
New User
Posts: 5
Joined: Tue Jun 21, 2022 5:19 pm

Pixelsorting in PureBasic

Post by knut_the_dude »

Hello forum,

I am new to PureBasic, coming from BlitzBasic, with a long time of no Basic coding at all in between. I wanted to experiment a little bit with with pixelsorting. I searched the web for existing PureBasic functions dealing with this topic, but I didn't find any. So I adapted a little piece of code that was originally written for Processing. Works like a charm for me. I want to present it to you. Maybe some of you find it useful. Maybe some others come up with ideas how to improve or elaborate it.

You will need some BMP image as input. Not too large, I suggest a size like 256x256 px for testing.

Code: Select all

; Adapted to PureBasic from https://happycoding.io/examples/p5js/images/pixel-sorter (user: Kevin)
; by knut_the_dude 2022.
; Be carefull with large images. For testing I recommend a size like maximum 256x256 pixels

EnableExplicit

#Image  = 0
Global SourceFilePath$   = "path-to-your\image.bmp"
Global OutputFile$       = ""

Declare PIXELSORT_1()

LoadImage(#Image,SourceFilePath$)
PIXELSORT_1()
OutputFile$ = GetPathPart(SourceFilePath$) + GetFilePart(SourceFilePath$,#PB_FileSystem_NoExtension) + "_sorted_" + Date() + ".bmp"
SaveImage(#Image, OutputFile$, #PB_ImagePlugin_BMP)

Procedure PIXELSORT_1()
     
     Protected w,h,x,y,moshFactor,colorPixelOne,colorPixelTwo,totalPixels,totalPixelOne,totalPixelTwo,i
     
     moshFactor = 20    ; Multiplied with total number of pixels, so many times the sort loop will iterate
                         ; Be carefull with high values. If the image size is 256x256, I suggest a 
                         ; moshFactor between 10 and 200 for testing.
     
     w = ImageWidth(#Image) : h = ImageHeight(#Image)
     totalPixels = w * h
     StartDrawing(ImageOutput(#Image))
     
     For i = 0 To (totalPixels * moshFactor)
       
          ; Get a random pixel.
          x = Random(w - 1);
          y = Random(h - 2);
          
          ; Get the color of the pixel.
          colorPixelOne = Point(x, y)
          
          ; Get the color of the pixel below the first one.
          colorPixelTwo = Point(x, y + 1)
          
          ; Get the total R+G+B of both colors.
          totalPixelOne = Red(colorPixelOne) + Green(colorPixelOne) + Blue(colorPixelTwo)
          totalPixelTwo = Red(colorPixelTwo) + Green(colorPixelTwo) + Blue(colorPixelTwo)
          
          ; If the first total is less than the second total, Swap the pixels.
          ; This causes darker colors To fall To the bottom,
          ; And light pixels To rise To the top.
          If (totalPixelOne < totalPixelTwo) 
               Plot(x, y, colorPixelTwo)
               Plot(x, y + 1, colorPixelOne)
          EndIf

     Next
StopDrawing()
  
EndProcedure
Regards,
knut_the_dude