2

I'm fairly new to APL and I would like to convert a 4x4 binary matrix into an image composed of black and white squares - the sort of thing found here. Documentation says that it's possible using ⎕WC to create a GUI object and then stating the Bits required? I can't find any examples, though there are some for opening picture files.

Please could someone provide an example using the returned matrix from this APL expression?

4 4 ⍴ 1 0 1 0

Thanks!

Adám
  • 6,573
  • 20
  • 37
awyr_agored
  • 613
  • 3
  • 19

2 Answers2

3

Given your matrix, matrix←4 4 ⍴ 1 0 1 0

Each RGB pixel is encoded as a single integer in base 256: cb ← matrix × 256 ⊥ 255 255 255

Now we create the bitmap: 'bm' ⎕WC 'Bitmap' ('CBits' cb)

And create the content of the corresponding PNG: png ← bm.MakePNG

Let's create a native (i.e. non-APL) container file and catch its tie number: tn ← '\tmp\pic.png' ⎕NCREATE ¯1

Appending the data: png ⎕NAPPEND tn

Untying the file: ⎕NUNTIE tn

Here's all the code together as a program that takes the filename as left argument and the mask as right argument:

∇ filename PNG matrix ; cb ; bm ; png ; tn
  cb ← matrix × 256 ⊥ 255 255 255
  'bm' ⎕WC 'Bitmap' ('CBits'cb)
  png ← bm.MakePNG
  tn ← filename ⎕NCREATE ¯1
  png ⎕NAPPEND tn
  ⎕NUNTIE tn
∇

However, you may want to scale the image a bit to actually be able to see it, so let's define a helper function that does the scaling:

Scale ← { ⍺ / ⍺ ⌿ ⍵ }

Now let's try it:

'\tmp\bigpic.png' PNG 100 Scale 3 3 ⍴ 1 0 1 1 1 0 0 0 0
]Open \tmp\bigpic.png

Windows Photos Screenshot

Here is a program that instead displays the picture in a separate window:

∇ Show matrix ; cb ; bm
  cb ← matrix × 256 ⊥ 255 255 255
  'bm' ⎕WC 'Bitmap' ('CBits'cb)
  'f' ⎕WC 'Form' ('Coord' 'ScaledPixel') ('Size' (⍴ matrix))
  'f.img' ⎕WC 'Image' ('Points' 0 0) ('Picture' bm)
∇

So we can do:

  Show 100 Scale 3 3 ⍴ 1 0 1 1 1 0 0 0 0

Dyalog APL GUI Form Screenshot

The full documentation for the Bitmap object is available online by entering ]Help Bitmap or offline by typing Bitmap and pressing the F1 key.

Adám
  • 6,573
  • 20
  • 37
  • Wow - awesome! Thank you @Adám I appreciate your time and effort. I was going to ask about scaling too but you beat me to it. – awyr_agored May 05 '19 at 03:19
2

one way to do this is to format the matrix as netpbm:

      a←4 4⍴1 0
      img←'P1'(⍕⌽⍴a),⍕¨↓a
      ⍪img
 P1
 4 4
 1 0 1 0
 1 0 1 0
 1 0 1 0
 1 0 1 0

write it to a file:

      (⊂img)⎕nput'a.pnm'

and use pnm2png or an online tool to convert it to a more popular format

ngn
  • 7,763
  • 6
  • 26
  • 35