Author Topic: Image functions: Convert Cartesian to Polar coordinates  (Read 221 times)

0 Members and 1 Guest are viewing this topic.

Offline loudar

  • Newbie
  • Posts: 73
  • improve it bit by bit.
Image functions: Convert Cartesian to Polar coordinates
« on: October 15, 2021, 03:16:20 PM »
I wrote this function as part of Vedit, the image editor made in QB64, but I wanted to share it because I can't recall seeing one like it here. I used the Wiki example for modifying image data in memory and adapted it to read the pixel data, then write them back into a new image with a bit of math for the new x and y coordinates.

Enjoy!

Code: QB64: [Select]
  1. SUB RectangleToPolar (Image AS LONG)
  2.     IF R < 0 OR R > 1 OR G < 0 OR G > 1 OR B < 0 OR B > 1 OR _PIXELSIZE(Image) <> 4 THEN EXIT SUB
  3.     DIM Buffer AS _MEM: Buffer = _MEMIMAGE(Image) 'Get a memory reference to our image
  4.  
  5.     maxx = _WIDTH(Image)
  6.     maxy = _HEIGHT(Image)
  7.     mx = maxx / 2
  8.     my = maxy / 2
  9.  
  10.     DIM O AS _OFFSET, O_Last AS _OFFSET
  11.     O = Buffer.OFFSET 'We start at this offset
  12.     O_Last = Buffer.OFFSET + maxx * maxy * 4 'We stop when we get to this offset
  13.     DIM imgPoints(maxy, maxx, 0 TO 3) AS _UNSIGNED _BYTE
  14.     DIM p, maxp AS _UNSIGNED _INTEGER64
  15.     maxp = maxx * maxy
  16.     'use on error free code ONLY!
  17.     DO
  18.         p = p + 1
  19.         y = FIX((p / maxp) * maxy)
  20.         x = p - (FIX((p / maxp) * maxy) * maxx)
  21.         imgPoints(y, x, 0) = _MEMGET(Buffer, O, _UNSIGNED _BYTE)
  22.         imgPoints(y, x, 1) = _MEMGET(Buffer, O + 1, _UNSIGNED _BYTE)
  23.         imgPoints(y, x, 2) = _MEMGET(Buffer, O + 2, _UNSIGNED _BYTE)
  24.         imgPoints(y, x, 3) = _MEMGET(Buffer, O + 3, _UNSIGNED _BYTE)
  25.         O = O + 4
  26.     LOOP UNTIL O = O_Last
  27.     'create new image
  28.     DIM newImg AS LONG
  29.     newImg = _NEWIMAGE(maxx, maxy, 32)
  30.     prevDest& = _DEST
  31.     _DEST newImg
  32.     COLOR _RGBA(0, 0, 0, 255), _RGBA(0, 0, 0, 0)
  33.     CLS
  34.     scaley = (maxx / 2 / _PI)
  35.     IF scaley > maxy THEN scaley = maxy / 2
  36.     y = -1: DO: y = y + 1
  37.         yfactor = (1 - (y / (maxy))) * scaley
  38.         x = -1: DO: x = x + 1
  39.             PSET (mx - (yfactor * SIN(2 * _PI * (1 - (x / maxx)))), my - (yfactor * COS(2 * _PI * (1 - (x / maxx))))), _RGBA(imgPoints(y, x, 2), imgPoints(y, x, 1), imgPoints(y, x, 0), imgPoints(y, x, 3))
  40.         LOOP UNTIL x = maxx
  41.     LOOP UNTIL y = maxy
  42.     _DEST Image
  43.     COLOR _RGBA(0, 0, 0, 255), _RGBA(0, 0, 0, 0)
  44.     CLS
  45.     _PUTIMAGE (0, 0)-(maxx, maxy), newImg, Image
  46.     _FREEIMAGE newImg
  47.     ERASE imgPoints
  48.     DIM imgPoints(0, 0, 0) AS _UNSIGNED _BYTE
  49.     _DEST prevDest&
  50.     'turn checking back on when done!
  51.     _MEMFREE Buffer
Check out what I do besides coding: http://loudar.myportfolio.com/