Data update

This commit is contained in:
Ingy döt Net 2026-04-30 12:34:36 -04:00
parent 4bb20c9b71
commit cbaf4c4b64
12390 changed files with 318560 additions and 27248 deletions

View file

@ -0,0 +1,70 @@
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
function Get_PPM (File : File_Type) return Image is
use Ada.Characters.Latin_1;
use Ada.Integer_Text_IO;
function Get_Line return String is -- Skips comments
Byte : Character;
Buffer : String (1..80);
begin
loop
for I in Buffer'Range loop
Character'Read (Stream (File), Byte);
if Byte = LF then
exit when Buffer (1) = '#';
return Buffer (1..I - 1);
end if;
Buffer (I) := Byte;
end loop;
if Buffer (1) /= '#' then
raise Data_Error;
end if;
end loop;
end Get_Line;
Height : Integer;
Width : Integer;
begin
if Get_Line /= "P6" then
raise Data_Error;
end if;
declare
Line : String := Get_Line;
Start : Integer := Line'First;
Last : Positive;
begin
Get (Line, Width, Last); Start := Start + Last;
Get (Line (Start..Line'Last), Height, Last); Start := Start + Last;
if Start <= Line'Last then
raise Data_Error;
end if;
if Width < 1 or else Height < 1 then
raise Data_Error;
end if;
end;
if Get_Line /= "255" then
raise Data_Error;
end if;
declare
Result : Image (1..Height, 1..Width);
Buffer : String (1..Width * 3);
Index : Positive;
begin
for I in Result'Range (1) loop
String'Read (Stream (File), Buffer);
Index := Buffer'First;
for J in Result'Range (2) loop
Result (I, J) :=
( R => Luminance (Character'Pos (Buffer (Index))),
G => Luminance (Character'Pos (Buffer (Index + 1))),
B => Luminance (Character'Pos (Buffer (Index + 2)))
);
Index := Index + 3;
end loop;
end loop;
return Result;
end;
end Get_PPM;

View file

@ -0,0 +1,9 @@
declare
F1, F2 : File_Type;
begin
Open (F1, In_File, "city.ppm");
Create (F2, Out_File, "city_grayscale.ppm");
Put_PPM (F2, Color (Grayscale (Get_PPM (F1))));
Close (F1);
Close (F2);
end;

View file

@ -46,11 +46,11 @@ loop % width * height
if (j == width)
{
j := 1
i += 1
j := 1
i += 1
}
else
j++
j++
}
return bitmap
}

View file

@ -13,59 +13,59 @@
(defun read-ppm-file-header (file)
(with-open-file (s file :direction :input)
(do ((failure-count 0 (1+ failure-count))
(tokens nil (let ((t1 (read-header-chars s)))
(if (> (length t1) 0)
(cons t1 tokens)
tokens))))
((>= (length tokens) 4) (values (nreverse tokens)
(file-position s)))
(tokens nil (let ((t1 (read-header-chars s)))
(if (> (length t1) 0)
(cons t1 tokens)
tokens))))
((>= (length tokens) 4) (values (nreverse tokens)
(file-position s)))
(when (>= failure-count 10)
(error (format nil "File ~a does not seem to be a proper ppm file - maybe too many comment lines" file)))
(error (format nil "File ~a does not seem to be a proper ppm file - maybe too many comment lines" file)))
(when (= (length tokens) 1)
(when (not (or (string= (first tokens) "P6") (string= (first tokens) "P3")))
(error (format nil "File ~a is not a ppm file - wrong magic-number. Read ~a instead of P6 or P3 " file (first tokens))))))))
(when (not (or (string= (first tokens) "P6") (string= (first tokens) "P3")))
(error (format nil "File ~a is not a ppm file - wrong magic-number. Read ~a instead of P6 or P3 " file (first tokens))))))))
(defun read-ppm-image (file)
(flet ((image-data-reader (stream start-position width height image-build-function read-function)
(file-position stream start-position)
(dotimes (row height)
(dotimes (col width)
(funcall image-build-function row col (funcall read-function stream))))))
(file-position stream start-position)
(dotimes (row height)
(dotimes (col width)
(funcall image-build-function row col (funcall read-function stream))))))
(multiple-value-bind (header file-pos) (read-ppm-file-header file)
(let* ((image-type (first header))
(width (parse-integer (second header) :junk-allowed t))
(height (parse-integer (third header) :junk-allowed t))
(max-value (parse-integer (fourth header) :junk-allowed t))
(image (make-rgb-pixel-buffer width height)))
(when (> max-value 255)
(error "unsupported depth - convert to 1byte depth with pamdepth"))
(cond ((string= "P6" image-type)
(with-open-file (stream file :direction :input :element-type '(unsigned-byte 8))
(image-data-reader stream
file-pos
width
height
#'(lambda (w h val)
(setf (rgb-pixel image w h) val))
#'(lambda (stream)
(make-rgb-pixel (read-byte stream)
(read-byte stream)
(read-byte stream))))
image))
((string= "P3" image-type)
(with-open-file (stream file :direction :input)
(image-data-reader stream
file-pos
width
height
#'(lambda (w h val)
(setf (rgb-pixel image w h) val))
#'(lambda (stream)
(make-rgb-pixel (read stream)
(read stream)
(read stream))))
image))
(t 'unsupported))
(width (parse-integer (second header) :junk-allowed t))
(height (parse-integer (third header) :junk-allowed t))
(max-value (parse-integer (fourth header) :junk-allowed t))
(image (make-rgb-pixel-buffer width height)))
(when (> max-value 255)
(error "unsupported depth - convert to 1byte depth with pamdepth"))
(cond ((string= "P6" image-type)
(with-open-file (stream file :direction :input :element-type '(unsigned-byte 8))
(image-data-reader stream
file-pos
width
height
#'(lambda (w h val)
(setf (rgb-pixel image w h) val))
#'(lambda (stream)
(make-rgb-pixel (read-byte stream)
(read-byte stream)
(read-byte stream))))
image))
((string= "P3" image-type)
(with-open-file (stream file :direction :input)
(image-data-reader stream
file-pos
width
height
#'(lambda (w h val)
(setf (rgb-pixel image w h) val))
#'(lambda (stream)
(make-rgb-pixel (read stream)
(read stream)
(read stream))))
image))
(t 'unsupported))
image))))
(export 'read-ppm-image)

View file

@ -0,0 +1,51 @@
require "./pixmap"
class Pixmap
def self.load_ppm (io)
blanks = StaticArray[9, 10, 11, 12, 13, 32]
magic = Bytes.new(3)
io.read magic
raise "Invalid format" unless magic[0] == 'P'.ord &&
magic[1] == '6'.ord &&
magic[2].in? blanks
data = io.getb_to_end
pos = 0
get_number = -> : Int32 {
start = pos
loop do # skip blanks and comments
case data[start]
when .in? blanks then start += 1
when '#'.ord
while data[start] != 10
start += 1
end
else break
end
end
stop = start
until data[stop].in? blanks
stop += 1
end
pos = stop
String.new(data[start..stop]).to_i
}
begin
width = get_number.call
height = get_number.call
maxval = get_number.call
rescue ex
raise "Bad P6 file"
end
raise "Unsupported color depth" unless maxval = 255
pos += 1
raise "Invalid data" unless (data.size - pos) % 3 == 0
len = (data.size - pos) // 3
raise "Bad bounds" unless len == width * height
pixels = Array(Color).new(len) { |i|
Color.new(data[i*3 + pos], data[i*3 + pos + 1], data[i*3 + pos + 2])
}
Pixmap.new width, height, pixels
end
register_loader ".ppm", load_ppm
end

View file

@ -0,0 +1,41 @@
include get.e
function get2(integer fn)
sequence temp
temp = get(fn)
return temp[2] - temp[1]*temp[1]
end function
function read_ppm(sequence filename)
sequence image, line
integer dimx, dimy, maxcolor
atom fn
fn = open(filename, "rb")
if fn < 0 then
return -1 -- unable to open
end if
line = gets(fn)
if not equal(line,"P6\n") then
return -1 -- only ppm6 files are supported
end if
dimx = get2(fn)
if dimx < 0 then
return -1
end if
dimy = get2(fn)
if dimy < 0 then
return -1
end if
maxcolor = get2(fn)
if maxcolor != 255 then
return -1 -- maxcolors other then 255 are not supported
end if
image = repeat(repeat(0,dimy),dimx)
for y = 1 to dimy do
for x = 1 to dimx do
image[x][y] = getc(fn)*#10000 + getc(fn)*#100 + getc(fn)
end for
end for
close(fn)
return image
end function

View file

@ -0,0 +1,5 @@
sequence image
image = read_ppm("image.ppm")
image = to_gray(image)
image = to_color(image)
write_ppm("image_gray.ppm",image)

View file

@ -8,11 +8,11 @@ blobsize = INSTR(FILEGET, "\n255\n") + 4 ' Get sizeof PPM header
head = @FILEGET + blobsize: tail = @FILEGET + FILELEN ' Set loop bounds
FOR ptr = head TO tail STEP 3 ' Transform color triplets
r = PEEK(ptr + 0, 1) ' Read colors stored in RGB order
g = PEEK(ptr + 1, 1)
b = PEEK(ptr + 2, 1)
l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' Derive luminance
POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' Write grayscale
r = PEEK(ptr + 0, 1) ' Read colors stored in RGB order
g = PEEK(ptr + 1, 1)
b = PEEK(ptr + 2, 1)
l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' Derive luminance
POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' Write grayscale
NEXT
FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer

View file

@ -3,7 +3,7 @@
s" P6" compare abort" Only P6 supported."
pad dup 80 fid read-line throw 0= abort" Partial line"
0. 2swap >number
1 /string \ skip space
1 /string \ skip space
0. 2swap >number
2drop drop nip ( w h )
bitmap { bmp }

View file

@ -12,32 +12,32 @@ import javax.imageio.ImageIO;
public class ReadPPMFile {
public static void main(String[] aArgs) throws IOException {
public static void main(String[] aArgs) throws IOException {
// Using the file created in the Bitmap task
String filePath = "output.ppm";
reader = new BufferedInputStream( new FileInputStream(filePath) );
final char header1 = (char) reader.read();
String filePath = "output.ppm";
reader = new BufferedInputStream( new FileInputStream(filePath) );
final char header1 = (char) reader.read();
final char header2 = (char) reader.read();
final char header3 = (char) reader.read();
if ( header1 != 'P' || header2 != '6' || header3 != END_OF_LINE) {
reader.close();
throw new IllegalArgumentException("Not a valid P6 PPM file");
reader.close();
throw new IllegalArgumentException("Not a valid P6 PPM file");
}
final int width = processCharacters(SPACE_CHARACTER);
final int height = processCharacters(END_OF_LINE);
final int maxColorValue = processCharacters(END_OF_LINE);
if ( maxColorValue < 0 || maxColorValue > 255 ) {
reader.close();
throw new IllegalArgumentException("Maximum color value is outside the range 0..255");
reader.close();
throw new IllegalArgumentException("Maximum color value is outside the range 0..255");
}
// Remove any comments before reading data
reader.mark(1);
while ( reader.read() == START_OF_COMMENT ) {
while ( reader.read() != END_OF_LINE );
reader.mark(1);
while ( reader.read() != END_OF_LINE );
reader.mark(1);
}
reader.reset();
@ -47,10 +47,10 @@ public class ReadPPMFile {
byte[] buffer = new byte[width * 3];
for ( int y = 0; y < height; y++ ) {
reader.read(buffer, 0, buffer.length);
for ( int x = 0; x < width; x++ ) {
for ( int x = 0; x < width; x++ ) {
Color color = new Color(Byte.toUnsignedInt(buffer[x * 3]),
Byte.toUnsignedInt(buffer[x * 3 + 1]),
Byte.toUnsignedInt(buffer[x * 3 + 2]));
Byte.toUnsignedInt(buffer[x * 3 + 1]),
Byte.toUnsignedInt(buffer[x * 3 + 2]));
bitmap.setPixel(x, y, color);
}
}
@ -60,29 +60,29 @@ public class ReadPPMFile {
// Convert to gray scale and save to a file
bitmap.convertToGrayscale();
File grayFile = new File("outputGray.jpg");
ImageIO.write((RenderedImage) bitmap.getImage(), "jpg", grayFile);
}
private static int processCharacters(char aChar) throws IOException {
StringBuilder characters = new StringBuilder();
char ch;
while ( ( ch = (char) reader.read() ) != aChar ) {
if ( ch == START_OF_COMMENT ) {
while ( reader.read() != END_OF_LINE );
continue;
}
characters.append(ch);
}
return Integer.valueOf(characters.toString());
}
private static BufferedInputStream reader;
private static final char START_OF_COMMENT = '#';
private static final char SPACE_CHARACTER = ' ';
private static final char END_OF_LINE = '\n';
ImageIO.write((RenderedImage) bitmap.getImage(), "jpg", grayFile);
}
}
private static int processCharacters(char aChar) throws IOException {
StringBuilder characters = new StringBuilder();
char ch;
while ( ( ch = (char) reader.read() ) != aChar ) {
if ( ch == START_OF_COMMENT ) {
while ( reader.read() != END_OF_LINE );
continue;
}
characters.append(ch);
}
return Integer.valueOf(characters.toString());
}
private static BufferedInputStream reader;
private static final char START_OF_COMMENT = '#';
private static final char SPACE_CHARACTER = ' ';
private static final char END_OF_LINE = '\n';
}
final class BasicBitmapStorage {
@ -105,12 +105,12 @@ final class BasicBitmapStorage {
}
public Image getImage() {
return image;
return image;
}
public void convertToGrayscale() {
for ( int y = 0; y < image.getHeight(); y++ ) {
for ( int x = 0; x < image.getWidth(); x++ ) {
for ( int x = 0; x < image.getWidth(); x++ ) {
int color = image.getRGB(x, y);
int alpha = ( color >> 24 ) & 255;

View file

@ -10,31 +10,31 @@ define
F = {New Open.file init(name:Filename)}
fun {ReadColor8 _}
Bytes = {F read(list:$ size:3)}
Bytes = {F read(list:$ size:3)}
in
{List.toTuple color Bytes}
{List.toTuple color Bytes}
end
fun {ReadColor16 _}
Bytes = {F read(list:$ size:6)}
Bytes = {F read(list:$ size:6)}
in
{List.toTuple color {Map {PairUp Bytes} FromBytes}}
{List.toTuple color {Map {PairUp Bytes} FromBytes}}
end
in
try
Magic = {F read(size:2 list:$)}
if Magic \= "P6" then raise bitmapIO(read unsupportedFormat(Magic)) end end
Width = {ReadNumber F}
Height = {ReadNumber F}
MaxVal = {ReadNumber F}
MaxVal =< 0xffff = true
Reader = if MaxVal =< 0xff then ReadColor8 else ReadColor16 end
B = {Bitmap.new Width Height}
Magic = {F read(size:2 list:$)}
if Magic \= "P6" then raise bitmapIO(read unsupportedFormat(Magic)) end end
Width = {ReadNumber F}
Height = {ReadNumber F}
MaxVal = {ReadNumber F}
MaxVal =< 0xffff = true
Reader = if MaxVal =< 0xff then ReadColor8 else ReadColor16 end
B = {Bitmap.new Width Height}
in
{Bitmap.transform B Reader}
B
{Bitmap.transform B Reader}
B
finally
{F close}
{F close}
end
end
@ -43,12 +43,12 @@ define
in
{SkipWS F}
Ds = for collect:Collect break:Break do
[C] = {F read(list:$ size:1)}
in
if {Char.isDigit C} then {Collect C}
else {Break}
end
end
[C] = {F read(list:$ size:1)}
in
if {Char.isDigit C} then {Collect C}
else {Break}
end
end
{SkipWS F}
{String.toInt Ds}
end
@ -58,9 +58,9 @@ define
in
if {Char.isSpace C} then {SkipWS F}
elseif C == &# then
{SkipLine F}
{SkipLine F}
else
{F seek(whence:current offset:~1)}
{F seek(whence:current offset:~1)}
end
end

View file

@ -7,8 +7,8 @@ class Bitmap {
role PGM {
has @.GS;
method P5 returns Blob {
"P5\n{self.width} {self.height}\n255\n".encode('ascii')
~ Blob.new: self.GS
"P5\n{self.width} {self.height}\n255\n".encode('ascii')
~ Blob.new: self.GS
}
}

View file

@ -0,0 +1,50 @@
Rebol [
title: "Rosetta code: Bitmap/Read a PPM file"
file: %Bitmap-Read_a_PPM_file.r3
url: https://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
]
decode-ppm: function[ppm [string! file! url!]][
;; Load source into a string if a file or URL was given
unless string? ppm [ppm: read/string ppm]
if all [
;; Strip the "P3" magic header and any comment lines
parse/case ppm ["P3" any [LF | #"#" to LF skip] ppm: to end]
;; Lex the remaining text into Rebol values
try [ppm: transcode ppm]
;; Extract image dimensions, colour depth, and raw RGB values
parse ppm [
set width: integer!
set height: integer!
set depth: integer!
rgb: to end
]
][
img: make image! as-pair width height
i: 1 clr: 0.0.0
foreach [r g b] rgb [
;; Normalise each channel to 0255
clr/1: 255 * (r / depth)
clr/2: 255 * (g / depth)
clr/3: 255 * (b / depth)
img/:i: clr
++ i
]
;; Return the completed image
img
]
]
img: decode-ppm {P3
# feep.ppm
4 4
15
0 0 0 0 0 0 0 0 0 15 0 15
0 0 0 0 15 7 0 0 0 0 0 0
0 0 0 0 0 0 0 15 7 0 0 0
15 0 15 0 0 0 0 0 0 0 0 0}
print "Source image:"
print img
print "Grayscale PPM output:"
print to-ppm grayscale img ;@@ https://rosettacode.org/wiki/Bitmap/Write_a_PPM_file

View file

@ -6,7 +6,7 @@ import javax.swing.ImageIcon
object Pixmap {
private case class PpmHeader(format:String, width:Int, height:Int, maxColor:Int)
def load(filename:String):Option[RgbBitmap]={
implicit val in=new BufferedInputStream(new FileInputStream(filename))
val header=readHeader
@ -22,7 +22,7 @@ object Pixmap {
private def readHeader(implicit in:InputStream)={
var format=readLine
var line=readLine
while(line.startsWith("#")) //skip comments
line=readLine
@ -31,7 +31,7 @@ object Pixmap {
val width=parts(0).toInt
val height=parts(1).toInt
val maxColor=readLine.toInt
new PpmHeader(format, width, height, maxColor)
}

View file

@ -7,11 +7,11 @@
:LOAD_PPM:
File_Open(@10)
BOF
Search("|X", ADVANCE) // skip "P6"
#11 = Num_Eval(ADVANCE) // #11 = width
Match("|X", ADVANCE) // skip separator
#12 = Num_Eval(ADVANCE) // #12 = height
Search("|X", ADVANCE) // skip "P6"
#11 = Num_Eval(ADVANCE) // #11 = width
Match("|X", ADVANCE) // skip separator
#12 = Num_Eval(ADVANCE) // #12 = height
Match("|X", ADVANCE)
Search("|X", ADVANCE) // skip maxval (assume 255)
Del_Block(0,CP) // remove the header
Search("|X", ADVANCE) // skip maxval (assume 255)
Del_Block(0,CP) // remove the header
Return

View file

@ -1,27 +1,27 @@
sub readPPM(f$)
local ff, x, y, t$, dcol$, wid, hei
local ff, x, y, t$, dcol$, wid, hei
if f$ = "" print "No PPM file name indicate." : return false
if f$ = "" print "No PPM file name indicate." : return false
ff = open (f$, "rb")
if not ff print "File ", f$, " not found." : return false
ff = open (f$, "rb")
if not ff print "File ", f$, " not found." : return false
input #ff t$, wid, hei, dcol$
input #ff t$, wid, hei, dcol$
if t$ = "P6" then
open window wid, hei
for x = 0 to hei - 1
for y = 0 to wid - 1
color peek(#ff), peek(#ff), peek(#ff)
dot y, x
next y
next x
close #ff
else
print "File is NOT PPM P6 type." : return false
end if
return true
if t$ = "P6" then
open window wid, hei
for x = 0 to hei - 1
for y = 0 to wid - 1
color peek(#ff), peek(#ff), peek(#ff)
dot y, x
next y
next x
close #ff
else
print "File is NOT PPM P6 type." : return false
end if
return true
end sub