#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 13 11:38:15 2020 @author: andrea """ class Colore: def __init__(self, R, G, B): "inizializzazione: memorizza nell'istanza i valori di luminosità" self.R = R self.G = G self.B = B #self.colore = [R, G, B] def luminosita(self): return (self.R + self.G + self.B)//3 def grigio(self): "crea un colore grigio con la stessa luminosità" media = self.luminosita() #media = sum(self.colore)//3 return Colore(media, media, media) def __repr__(self): "torna la stringa da usare nelle stampe per visualizzare il coolore" return f"Colore({self.R}, {self.G}, {self.B})" #return f"Colore({self.colore})" def __mul__(self, k): "metodo che moltiplica tutte le componenti di un colore per un numero e produce il colore risultante" return Colore(self.R*k, self.G*k, self.B*k) def asTriple(self): "torna la terna di valori interi tra 0 e 255 per le immagini PNG" def bound(C): return min(255, max(0, round(C))) return bound(self.R), bound(self.G), bound(self.B) def __add__(self, other): "somma componente per componente di due colori" return Colore(self.R+other.R, self.G+other.G, self.B+other.B) def __sub__(self, other): "differenza componente per componente di due colori" return Colore(self.R-other.R, self.G-other.G, self.B-other.B) def contrasto(self, k): "aumenta/dimnuisce il contrasto di un fattore k" g = Colore(128,128,128) return ((self-g)*k)+g def negativo(self): white = Colore(255, 255, 255) return white - self def __lt__(self, other): return self.luminosita() < other.luminosita() def __eq__(self, other): return self.R == other.R and self.G == other.G and self.B == other.B class Immagine: def __init__(self, w, h, c=Colore(0,0,0)): "crea una immagine larga w e alta h con colore di sfondo c" self.w = w self.h = h self.img = [ [ c for x in range(w) ] for y in range(h) ] def __repr__(self): return f"Immagine( {self.w}, {self.h}, {self.img[0][0]} )" def bw(self): "crea una immagine in bianco e nero da quella originale" nuova = Immagine(self.w, self.h) for y, linea in enumerate(self.img): for x, pixel in enumerate(linea): nuova.img[y][x] = pixel.grigio() return nuova A = [ Colore(234, 17, 23), Colore(12, 45, 250), Colore(2, 56, 45)] print(Colore(14, 56, 71) == Colore(14, 56, 71)) print(sorted(A)) print(Immagine(100, 50, Colore(0,255,0)))