1 CSC 221: Introduction to Programming Fall 2012 Object-oriented programming  object-oriented approach classes & objects  user-defined classes example:

Slides:



Advertisements
Similar presentations
Creative Computing. \\ aims By the end of the session you will be able to: 1.Explain the difference between various image file formats 2.Load in and display.
Advertisements

1 CSC 221: Introduction to Programming Fall 2011 List comprehensions & objects building strings & lists comprehensions conditional comprehensions example:
Information Representation
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
Computer Science 111 Fundamentals of Programming I More Digital Image Processing.
The Binary Numbering Systems
The Web Warrior Guide to Web Design Technologies
Objectives Define photo editing software
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Connecting with Computer Science, 2e
Fundamentals of Python: From First Programs Through Data Structures
Steganography Rayan Ghamri.
Computer Science 111 Fundamentals of Programming I Introduction to Digital Image Processing.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 12 Data.
Games and Simulations O-O Programming in Java The Walker School
Connecting with Computer Science 2 Objectives Learn why numbering systems are important to understand Refresh your knowledge of powers of numbers Learn.
Chapter 3 Adding Images in HTML. Agenda Understanding Web Page Images Prepare Your Images for the Web Insert an Image Specify an Image Size Add Alternative.
1 CSC 221: Computer Programming I Fall 2004 Objects and classes: a first pass  software objects, classes, object-oriented design  BlueJ IDE, compilation.
Lecture 5.
1 Ethics of Computing MONT 113G, Spring 2012 Session 11 Graphics on the Web Limits of Computer Science.
Faculty of Sciences and Social Sciences HOPE Website Development Graphics Stewart Blakeway FML 213
Dean Pentcheff NHMLAC MBPC/Crustacea 17 April 2006.
COMP Bitmapped and Vector Graphics Pages Using Qwizdom.
CSCI-235 Micro-Computers in Science Hardware Part II.
Computers and Scientific Thinking David Reed, Creighton University Data Representation 1.
Lab #5-6 Follow-Up: More Python; Images Images ● A signal (e.g. sound, temperature infrared sensor reading) is a single (one- dimensional) quantity that.
1 Perception, Illusion and VR HNRS 299, Spring 2008 Lecture 14 Introduction to Computer Graphics.
1 CSC 221: Computer Programming I Spring 2010 Objects and classes: a broad view  Scratch programming review  object-oriented design, software objects.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 5 Working with Images Starting Out with Games & Graphics in.
Lecture 5. Topics Sec 1.4 Representing Information as Bit Patterns Representing Text Representing Text Representing Numeric Values Representing Numeric.
Computer Science 111 Fundamentals of Programming I Introduction to Graphics.
Computer Science 112 Fundamentals of Programming II Graphics Programming.
1 Ethics of Computing MONT 113G, Spring 2012 Session 10 HTML Tables Graphics on the Web.
Section 8.1 Create a custom theme Design a color scheme Use shared borders Section 8.2 Identify types of graphics Identify and compare graphic formats.
A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University ©2011 Pearson Prentice Hall ISBN Chapter 15 JavaScript.
Copyright (c) 2004 Prentice-Hall. All rights reserved. 1 Committed to Shaping the Next Generation of IT Experts. Adding Graphical Elements Essentials for.
Image Representation. Digital Cameras Scanned Film & Photographs Digitized TV Signals Computer Graphics Radar & Sonar Medical Imaging Devices (X-Ray,
1 CSC 221: Computer Programming I Spring 2008 Objects and classes: a broad view  software objects, classes, object-oriented design  BlueJ IDE, compilation.
Computer Science 111 Fundamentals of Programming I Introduction to Digital Image Processing.
10 | Graphics COM 366 Web Design & Production. Native file format –Format native to software program –psd > PhotoShop default Preserves layers –Use “Save.
1 CSC 222: Object-Oriented Programming Spring 2013 Objects and classes: a first pass  221 review  software objects, classes, object-oriented design 
Digital Media Dr. Jim Rowan ITEC So far… We have compared bitmapped graphics and vector graphics We have discussed bitmapped images, some file formats.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Adobe Photoshop CS5 – Illustrated Unit A: Getting Started with Photoshop CS5.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Project Two Adding Web Pages, Links, and Images Define and set a home page Add pages to a Web site Describe Dreamweaver's image accessibility features.
CSCI-100 Introduction to Computing Hardware Part II.
Data Representation. What is data? Data is information that has been translated into a form that is more convenient to process As information take different.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
Digital Media Dr. Jim Rowan ITEC Vector Graphics Elegant way to construct digital images that –have a compact representation –are scalable –are.
1 CSC 221: Computer Programming I Fall 2009 Objects and classes: a broad view  Scratch programming review  object-oriented design, software objects 
Image File Formats By Dr. Rajeev Srivastava 1. Image File Formats Header and Image data. A typical image file format contains two fields namely Dr. Rajeev.
Chapter 3: Data Representation Chapter 3 Data Representation Page 17 Computers use bits to represent all types of data, including text, numerical values,
Scanner Scanner Introduction: Scanner is an input device. It reads the graphical images or line art or text from the source and converts.
Graphics and Image Data Representations 1. Q1 How images are represented in a computer system? 2.
Adobe Photoshop CS4 – Illustrated Unit A: Getting Started with Photoshop CS4.
1 Sections 5.1 – 5.2 Digital Image Processing Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 15 JavaScript.
CSC 222: Object-Oriented Programming
Raster Images CPSC 1030.
CSC 222: Object-Oriented Programming
Data Representation.
Representing Images 2.6 – Data Representation.
Digital Media Dr. Jim Rowan ITEC 2110.
Fundamentals of Programming I Introduction to Digital Image Processing
Fundamentals of Python: First Programs
CSC 221: Introduction to Programming Fall 2018
CSC 221: Introduction to Programming Fall 2018
Presentation transcript:

1 CSC 221: Introduction to Programming Fall 2012 Object-oriented programming  object-oriented approach classes & objects  user-defined classes example: Die class  HW 7: OOP approach DeckOfCards, RowOfCards, skip3  Image class grayscale, b&w, negative, tint, reflect, randomize, … steganography: file splitting, embedding text

2 Object-oriented programming the dominant approach to (large-scale) software development today is object-oriented programming (OOP)  in order to solve a problem, you identify the objects involved in the real-world solution and model them in software e.g., if designing a banking system, model clients, accounts, deposits, …  a program is a collection of interacting objects  in software, objects are created from classes the class describes the kind of object (its properties and behaviors) the objects represent individual instantiations of the class classes & objects in Scratch: class: cat, baseball, die, …(collections of sprite templates) object: sprite1, rollButton, …(can create or stamp out instances) properties/fields: size, coords, costume, …(can view on stage and above scripts) behaviors/methods: turn, move, think, …(can execute by clicking script or flag)

3 Class & object examples  the class encompasses all automobiles they all have common properties: wheels, engine, brakes, … they all have common behaviors: can sit in them, start them, accelerate, steer, …  each car object has its own specific characteristics and ways of producing behaviors my car is white & seats 5; the batmobile is black & seats 2 accelerating with V-4 is different than accelerating with jet engine REAL WORLD CLASS: automobiles REAL WORLD OBJECTS: my 2011 Subaru Outback, the batmobile, … class or object?  student  Creighton University  Morrison Stadium  shoe

OO in Python 4 Python fully supports the object-oriented approach  useful classes are built-in, e.g., string, list  the programmer can define new classes to extend the language str class: properties/fields: the sequence of characters behaviors/methods: upper, lower, toupper, tolower, capitalize, strip, split, … >>> str1 = "foo"  shorthand for str1 = str("foo") >>> str1.upper() 'FOO' list class: properties/fields: the sequence of items behaviors/methods: sort, reverse, index, count,… >>> list1 = [2, 6, 4]  shorthand for list1 = list([2, 6, 4]) >>> list1.sort() >>> list1 [2, 4, 6]

Python class definition general form: class CLASSNAME: def __init__(self): self.FIELD1 = INITIAL_VALUE … self.FIELDn = INITIAL_VALUE def METHOD1(self): STATEMENTS … def METHODn(self): STATEMENTS 5 each method has an implicit parameter self, which refers to the object that the method is being applied to __init__ is a special method for initializing an object; it is automatically called when an object is created: obj = CLASSNAME() the fields (i.e., properties) of the object are variables with the prefix self., which implies that they belong to this object fields can be accessed by all the methods; they exist as long as the object does

Example: 6-sided die simple example: modeling a 6-sided die  properties/fields: number of rolls  behaviors/methods: rolls, numberOfRolls 6 convention: class names will start with uppercase; variables & functions with lowercase

Example: N-sided die can easily generalize the class to allow for different sided dice  properties/fields: number of sides, number of rolls  behaviors/methods: rolls, numberOfSides, numberOfRolls 7 note: each Die object has its own copies of the fields if a method has explicit parameters, place after self

OO view of Skip-3 can identify the objects involved in a Skip-3 game  Card  properties/fields: rank & suit  DeckOfCards  properties/fields: a sequence of cards (w/ top & bottom) behaviors/methods: shuffle, dealCard, numCards, …  RowOfCards  properties/fields: a sequence of cards (w/ left & right) behaviors/methods: addAtEnd, moveCard, numCards, … using these objects, can build an interactive game 8

cards.py 9 ranks & suits are local variables (belong to the function); self.cards is a field (belongs to the object) addCard has an explicit parameter: the card to add __str__ is a special-purpose method, converts the object to a string (used by print)

DeckOfCards example 10

HW 7: RowOfCards class similarly, we could define a class that represents a row of cards  you will complete the class definition for the first part of HW 7 11

HW 7: skip3 game in PART 2, extend the game framework add help command display # of cards in the row at "quit" add error checking to handle illegal & malformed commands 12

Another OOP example: digital images 13 representing images images are stored using a variety of formats and compression techniques the simplest representation is a bitmap bitmaps partition an image into a grid of picture elements, called pixels, and then convert each pixel into a bit pattern resolution refers to the sharpness or clarity of an image bitmaps that are divided into smaller pixels will yield higher resolution images the left image is stored using 72pixels per square inch, and the right image is stored using 36pixels per square inch  the left image appears sharp, but has twice the storage requirements

Color formats 14 when creating a bitmap of a color image, more than one bit is required to represent each pixel  the most common system is to translate each pixel into a 24 bit code, known as its RGB value : 8 bits to represent the intensity of each red/green/blue component common image formats implement various compression techniques to reduce storage size GIF (Graphics Interchange Format)  a lossless format, meaning no information is lost in the compression  commonly used for precise pictures, such as line drawings PNG(Portable Network Graphics)  more modern alternative to GIF - more colors, 10-50% more compact JPEG (Joint Photographic Experts Group)  a lossy format, so the compression is not fully reversible (but more efficient)  commonly used for photographs

Image class images.py contains the definition of a class for manipulating GIFs  developed by Ken Lambert at Washington & Lee University 15 Image(filename) Loads an image from the file named fileName and returns an Image object that represents this image. The file must exist in the current working directory. Image(width, height) Returns an Image object of the specified width and height with a single default color. getWidth() Returns the width of the image in pixels. getHeight() Returns the width of the image in pixels. getPixel(x, y) Returns the pixel at the specified coordinates. A pixel is of the form (r, g, b), where the letters are integers representing the red, green, and blue values of a color in the RGB system. setPixel(x, y, (r, g, b)) Resets the pixel at position (x, y) to the color value represented by (r, g, b). The coordinates must be in the range of the image's coordinates and the RGB values must range from 0 through 255. draw() Pops up a window and displays the image. The user must close the window to continue the program. clone() Returns an Image object that is an exact copy of the original object. save() Saves the image to its current file, if it has one. Otherwise, does nothing. save(filename) Saves the image to the given file and makes it the current file. This is similar to the Save As option in most File menus.

Image example to use, import the Image class from the images.py module  stored in the class Code folder as images.pytxtimages.pytxt  you must download a copy and rename as images.py 16 note: the Image class is meant to be simple, not Photoshop quality  the draw method opens a viewer window  can only view one image at a time  must close the viewer window in order to continue

Image = grid of pixels recall that an image is made up of a 2-dimensional grid of pixels  top-left corner is (0, 0)  top-right corner is (img.getWidth()-1, 0)  bottom-left corner is (0, img.getHeight()-1)  bottom-right corner is(img.getWidth()-1, img.getHeight()-1) 17 (0,0) (123,249) (123,0) (0,249)

Traversing the pixels can go through each pixel in an image using nested loops: 18 e.g., can obtain a photo negative by inverting each RGB number

Image tinting similar task, adjust the tint of the image  want to be able to change the RGB values uniformly for every pixel 19 PROBLEM?

Image tinting (cont.) problem: the RGB values must be in range  if attempt to set a pixel with values outside this range  ERROR  need to make sure that adding maxes out at 255 & subtracting mins out at 0 20

Converting to grayscale (v. 1) to store a grayscale image, really only need one value per pixel 0 is black … 64 is dark gray … 128 is gray … 192 is light gray … 255 is white can simulate this in a color image by having equal RGB values (0,0,0) … (64,64,64) … (128,128,128) … (192,192,192) … (255,255,255) to convert a color image to grayscale, simple approach:  for each pixel, replace RGB value with the average of the color RGB values 21

Converting to grayscale (v. 2) it turns out that the human eye is more sensitive to green, then red, then blue  the relative sensitivities have been determined experimentally  a better grayscale conversion uses a weighted average based on these 22

Exercise: converting to B&W to convert from color to black & white, for each pixel:  if the average RGB value < 128, then replace with black pixel: (0,0,0)  if the average RGB value ≥ 128, then replace with white pixel: (255,255,255) 23

Making static the following function replaces each pixel with a random B&W value 24 EXERCISE: implement a color version

Horizontal reflection suppose we want to add a mirror effect to the image  take the top half of the image, reflect it below  for each pixel (x,y) in the top half: copy its value to the corresponding (x, img.getHeight()-y) pixel in the bottom half 25 EXERCISE: implement reflectVertical

Pixel smoothing low resolution images can look bad due to pixilation  pixel smoothing can be used to blur the edges of an image, make it look "softer"  for each pixel, replace its RGB value with the average RGB value of that pixel and its 8 neighboring pixels 26

Smooth (v. 1) brute force solution 27

Smooth (v. 2) can be simplified using list comprehensions 28

GIF limitations the Image class imports a GIF file and stores internally as a pixelmap (i.e., a 2-D grid of pixels)  the draw method displays the internal pixelmap limitation of GIF files: can only store 256 unique color values  no problem for negative, makeGray1, makeGray2,, makeBW, randomBW, reflectHorizontal & reflectVertical these functions will not introduce more than 256 colors  potential problem for tint, randomColor, smooth these introduce new pixels, could exceed 256 different colors most image manipulation programs will save a > 256-color GIF by combining colors to get below the 256-color limit the Image class will allow you to continue transforming the internal image, but will cause an error when you try to save an image with > 256 colors 29

Color vs. grayscale 30

Images & steganography steganography is the art & science of hiding messages in plain sight  messages written in invisible ink or lemon juice  microdots hidden in the period on a page (WWII)  tattooing a message on a scalp, then growing hair to cover (ancient Greece)  SECRET MESSAGE: Caleb and Natalie yanked our underwear rather egregiously. Arnie didn't think his intelligence sufficed. 31 steganography can be applied to digital images as well as text  we can hide the contents of an image by splitting it into two (seemingly) random files of static  we can hide text (or even other images) inside the pixels of an image to avoid the 256-color limit of our Image class, we will limit ourselves to grayscale (but these techniques generalize to color JPGs as well)

Static files consider the following grayscale images  both are (seemingly) random static  if you found one on a hard drive or attached to an – no information! 32

Joining images while these files are random, they are not independent  if you add the pixels, you get a real image image(x,y) = (mystery1(x,y) + mystery2(x,y)) % 256  note the use of modulo arithmetic (using %) if the sum of any RGB values exceeds 255, wrap around to 0 e.g., (128, 128, 128) + (200, 200, 200)  (72, 72, 72) 33 + 

Join code note: the images should have the same dimensions  could we handle different sized images? how? 34

Split code splitting an image into two static files involves two steps 1.generating a completely random file of grayscale pixels 2.subtracting each of those random pixels from the image pixels (using %) 35

Exercise take your favorite GIF file  make it grayscale using makeGray, then save it  split it into two static images using splitGrayImage  join them back together using joinGrayImages note: when you split an image  the first split is completely chosen at random  when you subtract a random amount from a pixel, also get a random amount  both files are completely random when taken in isolation – they only have meaning when taken together now, discover the secret to acing the final exam (ace1.gif & ace2.gif) 36

Embedding text in an image are these squares the same color? no: top-left is (100,100,100) bottom-right is (101,101,101)  human eye can barely distinguish the difference  so, last digit in the grayscale number is not very significant  can use that digit to hide a message 37

Repurposing bits suppose we wanted to hide the message "Howdy" in an image  we can convert the message into bits using the ASCII code for each character ord("H")  72  ord("o")  111  … "Howdy"  idea: take the first 40 pixels in the image  replace the least significant bit in the pixel color with the corresponding bit in the message img(0,0) = (128, 128, 128)1 st message bit is 0, so change last bit in 128 to 0 since 128 is even, already ends in 0 so OK img(0,1) = (128, 128, 128)2 nd message bit is 1, so change last bit in 128 to 1 since 128 is even, need to add 1  (129,129,129) img(0,2) = (255, 255, 255)3 rd message bit is 0, so change last bit in 255 to 0 since 255 is odd, need to subtract 1  (254,254,254) 38

Embedding code before embedding the message,  must add a marker at end (#END#) so the extraction process knows when to stop 39

Extracting code when extracting the message  convert the bits to text, then strip off the letters up to the marker (#END#) 40 now, find the doubly secret message hidden in (ace1.gif & ace2.gif)