Jump to content

Grayscale image: Difference between revisions

fortran
m (<lang>)
(fortran)
Line 189:
loop
loop nip ;
 
=={{header|Fortran}}==
 
(These fragments should be added to <tt>RCImageBasic</tt> module, see [[Basic bitmap storage#Fortran|Basic bitmap storage]])
 
First let's define a new type; the <tt>sc</tt> stands for Single Channel, which can be luminance (as it is here).
 
<lang fortran> type scimage
integer, dimension(:,:), pointer :: channel
integer :: width, height
end type scimage</lang>
 
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. 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.
 
<lang fortran> interface alloc_img
module procedure alloc_img_rgb, alloc_img_sc
end interface
 
interface free_img
module procedure free_img_rgb, free_img_sc
end interface</lang>
 
Now we can define useful interfaces and subroutines more task-related:
 
<lang fortran> interface assignment(=)
module procedure rgbtosc, sctorgb
end interface</lang>
 
<lang fortran> subroutine alloc_img_sc(img, w, h)
type(scimage) :: img
integer, intent(in) :: w, h
 
allocate(img%channel(w, h))
img%width = w
img%height = h
end subroutine alloc_img_sc
 
subroutine free_img_sc(img)
type(scimage) :: img
 
if ( associated(img%channel) ) deallocate(img%channel)
end subroutine free_img_sc
 
subroutine rgbtosc(sc, colored)
type(rgbimage), intent(in) :: colored
type(scimage), intent(inout) :: sc
 
if ( ( .not. valid_image(sc) ) .and. valid_image(colored) ) then
call alloc_img(sc, colored%width, colored%height)
end if
 
if ( valid_image(sc) .and. valid_image(colored) ) then
sc%channel = floor(0.2126*colored%red + 0.7152*colored%green + &
0.0722*colored%blue)
end if
end subroutine rgbtosc
 
subroutine sctorgb(colored, sc)
type(scimage), intent(in) :: sc
type(rgbimage), intent(inout) :: colored
 
if ( ( .not. valid_image(colored) ) .and. valid_image(sc) ) then
call alloc_img_rgb(colored, sc%width, sc%height)
end if
 
if ( valid_image(sc) .and. valid_image(colored) ) then
colored%red = sc%channel
colored%green = sc%channel
colored%blue = sc%channel
end if
 
end subroutine sctorgb</lang>
 
'''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):
 
<lang fortran>type(scimage) :: gray
type(rgbimage) :: animage
 
gray = animage
animage = gray
call output_ppm(an_unit, animage)</lang>
 
=={{header|OCaml}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.