Grayscale image: Difference between revisions
m
syntax highlighting fixup automation
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 19:
{{trans|Python}}
<
Byte r, g, b
Line 82:
print(‘Grey:’)
bitmap.togreyscale()
print(bitmap.writeppmp3())</
{{out}}
Line 111:
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Tool Kit}}
<
PROC PrintB3(BYTE x)
Line 185:
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Grayscale_image.png Screenshot from Atari 8-bit computer]
Line 209:
=={{header|Ada}}==
<
Conversion to a grayscale image:
<
type Extended_Luminance is range 0..10_000_000;
Result : Grayscale_Image (Picture'Range (1), Picture'Range (2));
Line 230:
end loop;
return Result;
end Grayscale;</
Conversion to a color image:
<
Result : Image (Picture'Range (1), Picture'Range (2));
begin
Line 241:
end loop;
return Result;
end Color;</
=={{header|BASIC256}}==
[[Image:BASIC256_greyscale_Mona_Lisa.jpg|right]]
[[Image:BASIC256_greysacle_Grey_Mona_lisa.jpg|right]]
<
h = 188
name$ = "Mona_Lisa.jpg"
Line 268:
next x
imgsave "Grey_"+name$,"jpg"</
{{omit from|Batch File}}
Line 276:
[[Image:original_bbc.jpg|right]]
[[Image:greyscale_bbc.jpg|right]]
<
Height% = 200
Line 304:
col% = TINT(x%*2,y%*2)
SWAP ?^col%,?(^col%+2)
= col%</
=={{header|C}}==
Definition/interface for a grayscale image.
<
typedef luminance pixel1[1];
typedef struct {
Line 320:
grayimage alloc_grayimg(unsigned int, unsigned int);
grayimage tograyscale(image);
image tocolor(grayimage);</
The same as <tt>alloc_img</tt>, but for grayscale images.
<
{
grayimage img;
Line 332:
img->height = height;
return img;
}</
Convert from ''color'' image to ''grayscale'' image.
<
{
unsigned int x, y;
Line 358:
}
return timg;
}</
And back from a ''grayscale'' image to a ''color'' image.
<
{
unsigned int x, y;
Line 383:
}
return timg;
}</
'''Notes'''
* <tt>tocolor</tt> and <tt>tograyscale</tt> do not free the previous image, so it must be freed normally calling <tt>free_img</tt>. With a cast we can use the same function also for grayscale images, or we can define something like
<
* ''Luminance'' is rounded. Since the C implementation is based on unsigned char (256 possible values per components), L can be at most 255.0 and rounding gives 255, as we expect. Changing the color_component type would only change 256, 255.0 and 255 values here written in something else, the code would work the same.
Line 394:
=={{header|C sharp|C#}}==
To convert TO grayscale:
<
Bitmap tImage = new Bitmap("spectrum.bmp");
Line 411:
// Save
tImage.Save("spectrum2.bmp");
</syntaxhighlight>
=={{header|Clojure|Clojure}}==
<
(import '[java.io File]
'[javax.imageio ImageIO]
Line 453:
"test-gray-cloj.png"))
</syntaxhighlight>
=={{header|Common Lisp}}==
Use the function rgb-to-gray-image to convert a rgb-image as loaded by the function defined [[Bitmap/Read a PPM file#Common Lisp]]. The package identifier assumes that you have the package as defined in [[Basic bitmap storage#Common Lisp]]. With the function grayscale-image-to-pgm-file it is possible to write out the gray image as pgm file which can then be further processed.
<
(in-package #:rgb-pixel-buffer)
Line 483:
(export 'grayscale-image-to-pgm-file)
</syntaxhighlight>
=={{header|Crystal}}==
{{trans|Ruby}}
Extending [[Basic_bitmap_storage#Crystal]]
<
def to_grayscale
luminosity = (0.2126*@red + 0.7152*@green + 0.0722*@blue).to_i
Line 505:
gray
end
end</
=={{header|D}}==
This example uses the bitmap module defined in the [[Bitmap]] Task page.
<
import core.stdc.stdio, std.array, std.algorithm, std.string, std.ascii;
Line 626:
img2.rgb2grayImage.savePGM("quantum_frog_grey.pgm");
}
}</
=={{header|Delphi}}==
Line 635:
The code below extends the erlang module on [[Bitmap]] task. This module supports RGB and grayscale modes. RGB colors are specified as {rgb, R, G, B} and saved as bytes into an array. Grayscale colors are likewise specified as {gray, L} where L is luminance.
<
-export([new/2, fill/2, set_pixel/3, get_pixel/2, convert/2]).
Line 708:
convert(#bitmap{mode=Mode}=Bitmap, Mode) ->
Bitmap.
</syntaxhighlight>
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang="text">
>A=loadrgb("mona.jpg");
>insrgb(A);
Line 722:
>insrgb(grayscale(A));
>insrgb(A|grayscale(A));
</syntaxhighlight>
=={{header|Euphoria}}==
<
sequence color
for i = 1 to length(image) do
Line 744:
end for
return image
end function</
=={{header|Factor}}==
{{works with|Factor|0.99 2020-07-03}}
<
: rgb>gray ( matrix -- new-matrix )
Line 754:
: gray>rgb ( matrix -- new-matrix )
[ dup dup 3array ] matrix-map ;</
=={{header|FBSL}}==
24-bpp BMP-format P.O.T.-size image solution:
[[Image:FBSLLena.png|right]]
<
DIM head, tail, r, g, b, l, ptr, blobsize = 54 ' sizeof BMP file headers
Line 773:
NEXT
FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save buffer</
=={{header|Forth}}==
<
\ bdim, bwidth, bdata all work with graymaps
Line 831:
over i j rot b!
loop
loop nip ;</
=={{header|Fortran}}==
Line 839:
First let's define a new type; the <tt>sc</tt> stands for Single Channel, which can be luminance (as it is here).
<
integer, dimension(:,:), pointer :: channel
integer :: width, height
end type scimage</
In order to allow proper overloading, the following subroutines of the [[Basic bitmap storage#Fortran|storage]] should be renamed appending the <tt>_rgb</tt> suffix: valid_image, inside_image, alloc_img, free_img, fill_img, get_pixel, put_pixel, init_img. The ''single channel'' version would be named with the <tt>_sc</tt> suffix, then we should define the proper interfaces to use the already written code as before. Here there are only the interfaces and subroutines needed for the task.
<
module procedure alloc_img_rgb, alloc_img_sc
end interface
Line 852:
interface free_img
module procedure free_img_rgb, free_img_sc
end interface</
Now we can define useful interfaces and subroutines more task-related:
<
module procedure rgbtosc, sctorgb
end interface</
<
type(scimage) :: img
integer, intent(in) :: w, h
Line 904:
end if
end subroutine sctorgb</
'''Usage example''' (fragment) which can be used to convert from ''rgb'' image to ''grayscale'' image and back (since we only can output the ''rgb'' kind):
<
type(rgbimage) :: animage
! ... here we "load" or create animage
Line 916:
gray = animage
animage = gray
call output_ppm(an_unit, animage)</
=={{header|Fōrmulæ}}==
Line 928:
=={{header|FreeBASIC}}==
{{trans|BASIC256}}
<
Dim As String imagen = "Mona_Lisa.bmp"
Screenres ancho,alto,32
Line 947:
Bsave "Grey_"+imagen+".bmp",0
Sleep</
{{out}}
<pre>
Line 955:
=={{header|FutureBasic}}==
There are several ways to handle grayscaling images in FB. Here's a function that accepts any of a variety of color images — JPEG, TIFF, PNG, BMP, GIF, etc. — and converts them to grayscale. The function uses a convenient build-in Core Image filter to generate the optimized grayscale image. This code compiles as a standalone application featuring a window with two image views, one showing the original color image, and the other with the converted grayscale image. The app uses a relatively square color image of flowers. It proportionately resizes the image to fit the left hand image view, and displays the converted image in the right hand view.
<syntaxhighlight lang="text">
include resources "flowers.jpg"
Line 1,001:
HandleEvents
</syntaxhighlight>
Line 1,008:
=={{header|Go}}==
<
import (
Line 1,107:
}
return b
}</
For demonstration program see task [[Bitmap/Read a PPM file]].
=={{header|Haskell}}==
<
import Bitmap
Line 1,128:
toGrayImage :: Color c => Image s c -> ST s (Image s Gray)
toGrayImage = mapImage $ Gray . luminance</
A <tt>Gray</tt> image can be converted to an <tt>RGB</tt> image with <tt>Bitmap.RGB.toRGBImage</tt>, defined [[Basic bitmap storage|here]].
Line 1,138:
Grayscale image is stored as two-dimensional array of luminance values. Allowed luminance scale is the same as for the color bitmap; the functions below are neutral to scale.
<
NB. L = 0.2126*R + 0.7152*G + 0.0722*B
toGray=: [: <. +/ .*"1&0.2126 0.7152 0.0722
NB. converts grayscale image to the color image, with all channels equal
toColor=: 3 & $"0</
Example:
<syntaxhighlight lang
=={{header|Java}}==
<
for(int i=0; i<image.getWidth(); i++){
for(int j=0; j<image.getHeight(); j++){
Line 1,173:
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
HTML 5
Demonstration: https://repl.it/repls/NiceFaroffRockrat
<syntaxhighlight lang="javascript">
function toGray(img) {
let cnv = document.getElementById("canvas");
Line 1,202:
return cnv.toDataURL();
}
</syntaxhighlight>
=={{header|Julia}}==
'''Adhering to the Task Description'''
<syntaxhighlight lang="julia">
using Color, Images, FixedPointNumbers
Line 1,227:
imc = gray2rgb(imb)
imwrite(imc, "grayscale_image_rc.png")
</syntaxhighlight>
Rounding errors are unlikely to be an issue for <code>rgb2gray</code>. The calculation of <code>g</code> promotes it to the literal float type (typically <code>Float64</code>).
'''A More Idiomatic Approach'''
<syntaxhighlight lang="julia">
using Color, Images, FixedPointNumbers
Line 1,237:
imb = convert(Image{Gray{Ufixed8}}, ima)
imwrite(imb, "grayscale_image_julia.png")
</syntaxhighlight>
{{output}}
Line 1,250:
As it's not possible to recover the original colored image (because different combinations of RGB values could have produced the same luminance), I have not bothered with the reverse operation.
<
import java.io.File
Line 1,276:
val grayFile = File("bbc_gray.jpg")
ImageIO.write(image, "jpg", grayFile)
}</
{{out}}
Line 1,284:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
nomainwin
WindowWidth = 400
Line 1,306:
wait
[q] unloadbmp "clr":close #1:end
</syntaxhighlight>
=={{header|Lingo}}==
<
res = image(img.width, img.height, 8)
res.paletteRef = #grayScale
Line 1,327:
end repeat
return res
end</
=={{header|Lua}}==
<
local size_x, size_y = #bitmap, #bitmap[1]
local gray_im = {}
Line 1,356:
return bitmap
end</
=={{header|Maple}}==
Maple has builtin command for conversion from RGB to Grayscale image: ImageTools:-ToGrayScale, which uses gray = 0.30 red + 0.59 green + 0.11 blue, the following implementation uses the CIE formula. Note that the conversion back from GrayScale to RGB uses Maple's builtin command: ImageTools:-ToRGB.
<
#conversion forward
dimensions:=[upperbound(img)];
Line 1,375:
ToRGB(x);
#display the result
Embed(x);</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica has a built-in grayscale conversion function called "ColorConvert". This example does not use it since it appears the luminance calculation is different from the CIE spec. Grayscale to RGB "conversion" just changes the single channel grayscale image to a triple channel image.
<
toFakeRGB[L_Image] := ImageApply[{#, #, #}&, L] </
=={{header|MATLAB}}==
Built in colour to grayscale converter uses the following forumula:
0.2989*R + 0.5870*G + 0.1140*B
<
grayImage = rgb2gray(inputImage);</
=={{header|Nim}}==
The right way to proceed would have been to add the case of gray scale images to our Image type (using a “variant object” with a discriminator). But we didn’t want to change the Image type, so we have created a GrayImage type and duplicated most procedures.
<syntaxhighlight lang="nim">
import bitmap
import lenientops
Line 1,464:
# Convert it back to RGB in order to save it in PPM format using the available procedure.
var convertedImage = grayImage.toImage()
convertedImage.writePPM("output_gray.ppm")</
=={{header|OCaml}}==
Conversion to a grayscale image:
<
let width = Bigarray.Array2.dim1 r_channel
and height = Bigarray.Array2.dim2 r_channel in
Line 1,488:
done;
done;
(gray_channel)</
Conversion to a color image:
<
let width = Bigarray.Array2.dim1 gray_channel
and height = Bigarray.Array2.dim2 gray_channel in
Line 1,510:
r_channel,
g_channel,
b_channel)</
and functions to get/set a pixel:
<
(fun x y -> gray_channel.{x,y})
let gray_put_pixel_unsafe (gray_channel) v =
(fun x y -> gray_channel.{x,y} <- v)</
=={{header|Octave}}==
Line 1,524:
'''Use package''': image
<
grayImage = rgb2gray(inputImage);</
Differently from [[Grayscale image#MATLAB|MATLAB]], the grayscale is computed as mean of the three RGB values. Changing this non-optimal behaviour is a matter of fixing three lines in the <tt>rgb2gray.m</tt> file; since it's a GPL-ed code, here it is a semplified version (error checking, usage help, argument checking removed)
<
switch(class(rgb))
case "double"
Line 1,542:
function lum = luminance(rgb)
lum = 0.2126*rgb(:,:,1) + 0.7152*rgb(:,:,2) + 0.0722*rgb(:,:,3);
endfunction</
Original code of the <tt>rgb2gray.m</tt> in the image package version 1.0.8 is by Kai Habel (under the GNU General Public License)
Line 1,549:
We define a "graymap" as a two-dimensional array of floats. In module <code>"Grayscale.oz"</code>, we implement conversion functions from and to bitmaps:
<
import
Array2D
Line 1,575:
color(L L L)
end
end</
=={{header|Perl}}==
Line 1,583:
Since we are using Imlib2, this one '''does''' '''not''' implement really a gray-scale (single channel) storage; it only ''converts'' an RGB image to an RGB image with the same three colour components for each pixel (which result in a gray-scale-like image)
<
use strict;
Line 1,609:
$gscale->save("Lennagray.jpg");
exit 0;</
=={{header|Phix}}==
{{Trans|Euphoria}}
Requires read_ppm() from [[Bitmap/Read_a_PPM_file#Phix|Read a PPM file]] and write_ppm() from [[Bitmap/Write_a_PPM_file#Phix|Write a PPM file]].
<
function to_grey(sequence image)
Line 1,634:
sequence img = read_ppm("Lena.ppm")
img = to_grey(img)
write_ppm("LenaGray.ppm",img)</
=={{header|PHP}}==
Uses the [[Write ppm file#PHP|Bitmap class]] defined for writing a PPM file
<
public function toGrayscale(){
for ($i = 0; $i < $this->h; $i++){
Line 1,658:
$b->setPixel(0, 13, array(0,0,255));
$b->toGrayscale();
$b->writeP6('p6-grayscale.ppm');</
=={{header|PicoLisp}}==
<
(de ppm->pgm (Ppm)
(mapcar
Line 1,683:
'((G) (list G G G))
Y ) )
Pgm ) )</
<
(de pgmWrite (Pgm File)
(out File
Line 1,709:
# Convert to color image and write to .ppm file
(ppmWrite (pgm->ppm *Pgm) "img.ppm")</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
do j = 1 to hbound(image,1);
do i = 0 to hbound(image,2);
Line 1,724:
end;
end;
</syntaxhighlight>
=={{header|PureBasic}}==
<
Protected w, h, x, y, r, g, b, gray, color
Line 1,761:
Next
StopDrawing()
EndProcedure</
=={{header|Python}}==
Line 1,767:
Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
<
import io
ppmfileout = io.StringIO('')
Line 1,819:
254 254 254 31 31 31 254 254 254 254 254 254
'''</
=={{header|R}}==
{{libheader|pixmap}}
<
setAs("pixmapGrey", "pixmapRGB",
function(from, to){
Line 1,855:
# Convert back to "colour"
plot(p3 <- as(p2, "pixmapRGB"))</
=={{header|Racket}}==
Line 1,862:
I gave up on uploading to Rosetta Code.
<
#lang racket
(require racket/draw)
Line 1,904:
(color->gray rosetta)
(gray->color (color->gray rosetta))
</syntaxhighlight>
=={{header|Raku}}==
Line 1,910:
This script expects to be fed a P6 .ppm file name at the command line. It will convert it to grey scale and save it as a binary portable grey map (P5 .pgm) file.
<syntaxhighlight lang="raku"
my $in = open($filename, :r, :enc<iso-8859-1>) or die $in;
Line 1,928:
$in.close;
$out.close;
}</
Using the .ppm file from the [[Bitmap/Write a PPM file#Raku|Write a PPM file]] task:
Line 1,936:
Note: REXX uses decimal (characters) instead of binary for storing numbers, so there is no rounding (using
<br> characters to store numbers is almost the same as using decimal floating point).
<
blue= '00 00 ff'x /*define the blue color (hexadecimal).*/
@.= blue /*set the entire image to blue color.*/
Line 1,951:
end /*row*/ /* [↑] D2C convert decimal ───► char*/
end /*col*/ /* [↑] x%1 is the same as TRUNC(x) */
/*stick a fork in it, we're all done. */</
=={{header|Ruby}}==
Extending [[Basic_bitmap_storage#Ruby]]
<
def to_grayscale
luminosity = Integer(0.2126*@red + 0.7152*@green + 0.0722*@blue)
Line 1,972:
gray
end
end</
=={{header|Scala}}==
Uses the [[Basic_bitmap_storage#Scala|Scala Basic Bitmap Storage]] class.
<
def luminosity(c:Color)=(0.2126*c.getRed + 0.7152*c.getGreen + 0.0722*c.getBlue+0.5).toInt
Line 1,985:
image
}
}</
=={{header|Sidef}}==
{{trans|Perl}}
<
func tograyscale(img) {
Line 2,007:
var gscale = tograyscale(image)
gscale.set_quality(80)
gscale.save(output)</
=={{header|Tcl}}==
<!-- L = 0.2126·R + 0.7152·G + 0.0722·B -->
{{libheader|Tk}}
<
proc grayscale image {
Line 2,024:
}
}
}</
Photo images are always 8-bits-per-channel RGBA.
=={{header|Vedit macro language}}==
Conversion to a grayscale image.<br>
<
// #10 = buffer that contains image data
// On return:
Line 2,049:
Buf_Switch(#10)
}
Return</
Conversion to a color image.<br>
<
// #20 = buffer that contains image data
// On return:
Line 2,071:
Buf_Switch(#20)
}
Return</
=={{header|Visual Basic}}==
Line 2,077:
{{works with|Visual Basic|6}}
{{libheader|Win32}}
<
Private Type BITMAP
Line 2,133:
DeleteDC hdc
End Sub</
=={{header|Visual Basic .NET}}==
Line 2,139:
Convert a Bitmap to Grayscale.
<
Imports System.Drawing.Imaging
Line 2,196:
Map.UnlockBits(oBMPData)
End Sub</
=={{header|Wren}}==
{{libheader|DOME}}
This script converts the image [https://rosettacode.org/File:Lenna100.jpg Lenna100.jpg] to grayscale and then displays the two images side by side.
<
import "dome" for Window
Line 2,240:
}
var Game = PercentageDifference.new(1100, 550, "Lenna100.jpg", "Lenna-grayscale.jpg")</
=={{header|Yabasic}}==
{{trans|BASIC256}}
"image" is a library created by Hermang Mansilla for import and show .BMP files. http://www.oocities.org/sunsetstrip/palms/1624/yabasic/libs/IMAGE.TXT
<
open window 600,600
Line 2,264:
dot x+300,y+300
next y
next x</
=={{header|zkl}}==
Line 2,273:
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
{{trans|BASIC256}}
<
foreach x,y in (img.w,img.h){
r,g,b:=img[x,y].toBigEndian(3);
Line 2,279:
img[x,y]=((lum*256) + lum)*256 + lum;
}
}</
<
toGrayScale(img);
img.write(File("foo.ppm","wb"));</
{{out}}
http://www.zenkinetic.com/Images/RosettaCode/lenaGray.jpg
|