100% found this document useful (9 votes)
1K views

Raspberry PI Computer Vision Programming 1st Edition Pajankar Ebook All Chapters PDF

Raspberry

Uploaded by

baxlulantina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (9 votes)
1K views

Raspberry PI Computer Vision Programming 1st Edition Pajankar Ebook All Chapters PDF

Raspberry

Uploaded by

baxlulantina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Get ebook downloads in full at ebookname.

com

Raspberry PI Computer Vision Programming 1st


Edition Pajankar

https://ebookname.com/product/raspberry-pi-computer-vision-
programming-1st-edition-pajankar/

OR CLICK BUTTON

DOWNLOAD EBOOK

Explore and download more ebook at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Raspberry Pi Gaming 2nd Edition Design create and play


all kinds of video games on your Raspberry Pi computer
Shea Silverman

https://ebookname.com/product/raspberry-pi-gaming-2nd-edition-
design-create-and-play-all-kinds-of-video-games-on-your-
raspberry-pi-computer-shea-silverman/

Raspberry Pi Robotics Essentials 1st Edition Grimmett

https://ebookname.com/product/raspberry-pi-robotics-
essentials-1st-edition-grimmett/

Raspberry Pi LED Blueprints 1st Edition Kurniawan

https://ebookname.com/product/raspberry-pi-led-blueprints-1st-
edition-kurniawan/

New Practical Chinese Reader Vol 1 3rd Ed 3rd Edition


Liu Xun

https://ebookname.com/product/new-practical-chinese-reader-
vol-1-3rd-ed-3rd-edition-liu-xun/
The Fundamentals of Interior Architecture First Edition
Naomi House

https://ebookname.com/product/the-fundamentals-of-interior-
architecture-first-edition-naomi-house/

Environmental Impact Assessment Methodologies 2nd


edition Y. Anjaneyulu

https://ebookname.com/product/environmental-impact-assessment-
methodologies-2nd-edition-y-anjaneyulu/

Operator Theory Functional Analysis and Applications


Operator Theory Advances and Applications 282 1st ed.
2021 Edition M. Amélia Bastos (Editor)

https://ebookname.com/product/operator-theory-functional-
analysis-and-applications-operator-theory-advances-and-
applications-282-1st-ed-2021-edition-m-amelia-bastos-editor/

Measure and Integration 1st Edition Leonard F.


Richardson

https://ebookname.com/product/measure-and-integration-1st-
edition-leonard-f-richardson/

A Treatise on Universal Algebra With Applications


Alfred North Whitehead

https://ebookname.com/product/a-treatise-on-universal-algebra-
with-applications-alfred-north-whitehead/
Toward Better Infrastructure Conditions Constraints and
Opportunities in Financing Public Private Partnerships
1st Edition Riham Shendy

https://ebookname.com/product/toward-better-infrastructure-
conditions-constraints-and-opportunities-in-financing-public-
private-partnerships-1st-edition-riham-shendy/
Raspberry Pi Computer Vision
Programming

Design and implement your own computer vision


applications with the Raspberry Pi

Ashwin Pajankar

BIRMINGHAM - MUMBAI
Raspberry Pi Computer Vision Programming

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2015

Production reference: 1250515

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78439-828-6

www.packtpub.com
Credits

Author Project Coordinator


Ashwin Pajankar Nikhil Nair

Reviewers Proofreaders
James Allen Stephen Copestake
Arush Kakkar Safis Editing
Luis A. Larco
Fred Stakem Indexer
Priya Sane
Aldo Vargas

Graphics
Commissioning Editor
Sheetal Aute
Amit Ghodake
Disha Haria

Acquisition Editor
Llewellyn Rozario Production Coordinator
Shantanu Zagade

Content Development Editor


Merwyn D'souza Cover Work
Shantanu Zagade

Technical Editor
Edwin Moses

Copy Editors
Puja Lalwani
Vedangi Narvekar
About the Author

Ashwin Pajankar is a Bangalore-based software professional with more than


5 years of experience in software design, development, testing, and automation.
He graduated from IIT Hyderabad with an MTech degree in computer science
and engineering. He holds multiple professional certifications from Oracle, IBM,
Teradata, and ISTQB in development, databases, and testing. Apart from work, he
enjoys serving the community. He has won several awards in college through college
outreach initiatives and at work for community service through his employers
for corporate social responsibility programs. He was introduced to the Raspberry
Pi while organizing a hackathon at his workplace, and he's been hooked on to Pi
ever since. He writes plenty of code in Bash, Python, and Java on his cluster of Pi.
Currently, he's building India's biggest cluster of the recently launched Raspberry
Pi 2. He's reviewed two other titles related to Python from Packt and is working on
another book on Raspberry Pi.

You can view Ashwin's LinkedIn profile by visiting in.linkedin.com/in/


ashwinpajankar.

I would like to thank my wife, Kavitha, for motivating me to


write this book to share my knowledge with others. I would also
like to thank Merwyn D'Souza and Llewellyn Rozario from Packt
Publishing for providing me with the opportunity, guidance, and
necessary support to write this book. Last but not least, I would like
to thank all the reviewers who helped me make the book better by
providing their precious feedback.
About the Reviewers

James Allen is a computer scientist and a teacher whose experiences run the gamut
from web and application programming to graphic design and sound engineering.
If a form of media can be produced on a computer, there is a very good chance that
he has dabbled in something along those lines.

He is very interested in the enabling factor of technology and how advancements


in personal computers and handheld devices have opened up a wide variety
of activities to a big chunk of the population. He is especially interested in
opening up these activities further. Above all, he wants to be happy and bring
happiness to others. You can read more about his (mis)adventures by visiting
http://jamesmallen.net.

Arush Kakkar is a robotics enthusiast who has experience in computer


vision, machine learning, and hardware technologies. His primary focus is
on autonomous robotics, which includes drones and self-driving cars. He has
contributed to the development of these systems in different capacities, including
computer vision and path planning. He is the electronics engineer for the solar car
team of his university, DTU Solaris. He is also interested in building commercial
solutions in robotics to reduce the manual labor required in jobs. You can contact
him through his website, www.arushkakkar.com, and read about some of his
projects on http://blog.arushkakkar.com.
Luis A. Larco is a software engineer at GE Healthcare in Milwaukee, Wisconsin,
as well as a research associate at the Medical Imaging Research Center (MIRC) at
the Illinois Institute of Technology in Chicago, Illinois. Originally from Lima, Peru,
Luis was raised in Miami, Florida, where he attended high school and college. He
subsequently relocated to Illinois and studied at the Illinois Institute of Technology.
He received bachelor’s degrees in electrical engineering and computer engineering.
While studying for his undergraduate degree, he worked on a research project
with the Chicago Police Department on predictive policing. In his free time, he
enjoys performing with his jazz band, where he plays the bass, as well as hiking
and mountain biking.

Aldo Vargas is a mechatronics engineer who graduated from UNAM in Mexico


City. He has previously worked in the robotics industry. He is currently completing
his PhD in aerospace engineering from the University of Glasgow, United
Kingdom. He is developing GNC (guidance, navigation, and control) algorithms for
unmanned aerial systems. The research aim is to give UAS the ability to "see" using
advanced and practical computer vision algorithms programmed in Python. He has
academic and industrial experience in control systems, embedded systems, artificial
intelligence, machine learning, computer vision, robotics, and systems integration.

Aldo loves to design, build, and control drones at work and during his free time.
He also enjoys scuba diving, skydiving, and riding motorcycles. If you're interested
in knowing more about his work, you can visit http://aldux.net.
www.PacktPub.com

Support files, eBooks, discount offers, and more


For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.com
and as a print book customer, you are entitled to a discount on the eBook copy. Get in
touch with us at service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.
TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.
Table of Contents
Preface v
Chapter 1: Introduction to Computer Vision and Raspberry Pi 1
Computer vision 1
OpenCV 2
Single-board computers and the Raspberry Pi 4
Raspberry Pi 4
Operating systems 5
Raspbian 6
Setting up your Raspberry Pi B+ 7
Preparing your microSD card manually 9
Booting up your Raspberry Pi for the first time 11
Shutting down and rebooting your Pi safely 12
Preparing your Pi for computer vision 13
Testing OpenCV installation with Python 15
NumPy 16
Array creation 16
Basic operations on arrays 17
Linear algebra 17
Summary 18
Chapter 2: Working with Images, Webcams, and GUI 19
Running Python programs with Raspberry Pi 19
Working with images 22
Using matplotlib 24
Drawing geometric shapes 26
Working with trackbar and named window 28
Working with a webcam 30
Creating a timelapse sequence using fswebcam 32
Webcam video recording and playback 34

[i]
Table of Contents

Working with a webcam using OpenCV 34


Saving a video and playback of a video using OpenCV 36
Working with the Pi camera module 37
Using raspistill and raspivid 37
Using picamera in Python with the Pi camera module 38
picamera and OpenCV 39
Summary 39
Chapter 3: Basic Image Processing 41
Retrieving image properties 41
Arithmetic operations on images 42
Blending and transitioning images 45
Splitting and merging image colour channels 47
Creating a negative of an image 48
Logical operations on images 50
Exercise 51
Summary 52
Chapter 4: Colorspaces, Transformations, and Thresholds 53
Colorspaces and conversions 53
Tracking in real time based on color 56
Image transformations 58
Scaling 58
Translation, rotation, and affine transformation 59
Perspective transformation 64
Thresholding image 66
Otsu's method 68
Exercise 69
Summary 70
Chapter 5: Let's Make Some Noise 71
Noise 71
Introducing noise to an image 72
Kernels 74
2D convolution filtering 74
Low-pass filtering 76
Exercise 79
Summary 79

[ ii ]
Table of Contents

Chapter 6: Edges, Circles, and Lines' Detection 81


High-pass filters 81
Canny Edge detector 85
Hough circle and line transforms 86
Exercise 90
Summary 90
Chapter 7: Image Restoration, Quantization, and Depth Map 91
Restoring images using inpainting 91
Image segmentation 93
Mean shift algorithm based segmentation 94
K-means clustering and image quantization 95
Comparison of mean shift and k-means 98
Disparity map and depth estimation 98
Summary 99
Chapter 8: Histograms, Contours, Morphological
Transformations, and Performance Measurement 101
Image histograms 101
Image contours 104
Morphological transformations on image 106
OpenCV performance measurement and improvement 107
Summary 108
Chapter 9: Real-life Computer Vision Applications 109
Barcode detection 109
Motion detection and tracking 117
Hand gesture recognition 121
Chroma key with green screen 126
Summary 132
Chapter 10: Introduction to SimpleCV 133
SimpleCV and its installation on Raspberry Pi 133
Getting started with the camera, display, and images 135
Binary thresholding and color distances 137
The blur effect on a live web camera feed 140
Histogram calculation 141
Greyscale conversion 142

[ iii ]
Table of Contents

Detecting corners and lines in an image 143


Blob detection in images 144
Sending Raspberry Pi on a boating vacation 145
Exercise 149
Summary 150
Index 151

[ iv ]
Preface
Raspberry Pi was developed as a low-cost single-board computer with the
intention of promoting computer science education in schools. It also represents
a welcome return to a simple and fun yet effective way to learn computer science
and programming.

You can use Raspberry Pi to learn and implement concepts in computer vision.

With a $35 Raspberry Pi computer and a USB webcam, anyone can afford to become
a pro in computer vision in no time and build a real-life computer vision application
to impress friends and colleagues.

What this book covers


Chapter 1, Introduction to Computer Vision and Raspberry Pi, takes you through the
introduction and initial setup of Raspberry Pi and computer vision.

Chapter 2, Working with Images, Webcams, and GUI, teaches you how to work with
images, videos, and various cameras.

Chapter 3, Basic Image Processing, explores arithmetic and logical operations on images.

Chapter 4, Colorspaces, Transformations, and Thresholds, introduces you to colorspaces


and conversions, which are then followed by a simple project. This chapter also
explores geometric transformations and segmentation by thresholding.

Chapter 5, Let's Make Some Noise, teaches the basics of noise in digital images and
low-pass filters. It also discussed their usage in the removal of noise from images.

Chapter 6, Edges, Circles, and Lines' Detection, explores high-pass filters and their
applications. It also explores the detection of features like edges, circles, and lines.

[v]
Preface

Chapter 7, Image Restoration, Quantization, and Depth Map, explores image restoration
by inpainting. It also teaches image segmentation, quantization, and depth maps.

Chapter 8, Histograms, Contours, Morphological Transformations, and Performance


Measurement, introduces the readers to histograms and plotting. It explores the
concepts of contours and morphological transformations on an image. It concludes
with the basics of performance measurement and improvement.

Chapter 9, Real-life Computer Vision Applications, implements various real-life


applications of computer vision using Raspberry Pi and a webcam.

Chapter 10, Introduction to SimpleCV, teaches the installation and usage of


SimpleCV, a powerful yet simple computer vision library, and concludes
with a few real-life projects.

What you need for this book


The following hardware is recommended for maximum enjoyment:

• The Raspberry Pi computer (Model B, B+, or Pi 2)


• SD card (8 GB minimum)
• 5V 1A power supply
• HDMI or VGA monitor
• HDMI to VGA converter if a VGA monitor is used
• Wired Internet connection
• A keyboard and a mouse
• A good quality webcam
• A Pi Camera
• A Windows computer/laptop with an embedded or external card reader

Who this book is for


This book is intended for novices as well as seasoned Raspberry Pi and Python
enthusiasts who would like to explore the area of computer vision. Readers with
very little programming or coding/scripting experience can create wonderful
image processing and computer vision applications with relatively few lines
of code in Python.

[ vi ]
Preface

Conventions
In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of
their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "
We are going to learn about the linspace() function now."

A block of code is set as follows:


import picamera
import time

with picamera.PiCamera() as cam:


cam.resolution=(1024,768)
cam.start_preview()
time.sleep(5)
cam.capture('/home/pi/book/output/still.jpg')

Any command-line input or output is written as follows:


>>> a**2
array([ 1, 9, 36, 81])

New terms and important words are shown in bold. Words that you see on the
screen, for example, in menus or dialog boxes, appear in the text like this: "Go to
Enable Boot to Desktop/Scratch | Desktop."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it helps
us develop titles that you will really get the most out of.

[ vii ]
Preface

To send us general feedback, simply e-mail feedback@packtpub.com, and mention


the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


You can download the example code files from your account at http://www.
packtpub.com for all the Packt Publishing books you have purchased. If you
purchased this book elsewhere, you can visit http://www.packtpub.com/support
and register to have the files e-mailed directly to you.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or added
to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/


content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

[ viii ]
Preface

Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected


pirated material.

We appreciate your help in protecting our authors and our ability to bring you
valuable content.

Questions
If you have a problem with any aspect of this book, you can contact us at
questions@packtpub.com, and we will do our best to address the problem.

[ ix ]
Introduction to Computer
Vision and Raspberry Pi
OpenCV is a simple yet powerful tool for any computer vision enthusiast. One can
learn computer vision in an easy way by writing OpenCV programs in Python.
The Raspberry Pi family of single-board computers uses Python as the preferred
development platform. Using a Raspberry Pi computer and Python for OpenCV
programming is one of the best ways to start your journey into the world of
computer vision. We will commence our journey with this chapter by getting
ourselves familiar with the following topics:

• Computer vision
• OpenCV
• Raspberry Pi
• Setting up Raspberry Pi
• Installing OpenCV and its dependencies
• NumPy basics

Computer vision
Computer vision is an area of computer science, mathematics, and electrical
engineering. It includes ways to acquire, process, analyze, and understand images
and videos from the real world in order to mimic human vision. Also, unlike
human vision, computer vision can also be used to analyze and process depth
and infrared images.

[1]
Introduction to Computer Vision and Raspberry Pi

Computer vision is also concerned with the theory of information extraction from
images and videos. A computer vision system can accept different forms of data as
an input, including, but not limited to, images, image sequences, and videos that can
be streamed from multiple sources to further process and extract useful information
from for decision making.

Artificial intelligence and computer vision share many topics, such as image
processing, pattern recognition, and machine learning techniques, as shown
in the following diagram:

The typical tasks of computer vision include the following:

• Object recognition and classification


• Motion detection and analysis
• Image and scene reconstruction

Don't worry about this jargon as of now. We will explore most of these concepts in
detail in the later chapters.

OpenCV
OpenCV (Open Source ComputerVision) is a library of programming functions
for computer vision. It was initially developed by the Intel Russia research center
in Nizhny Novgorod, and it is currently maintained by Itseez.

[2]
Chapter 1

You can read more about Itseez at http://itseez.com/.

This is a cross-platform library, which means that it can be implemented and


operated on different operating systems. It focuses mainly on image and video
processing. In addition to this, it has several GUI and event handling features for
the user's convenience.

OpenCV was released under a Berkeley Software Distribution (BSD) license and
hence, it is free for both academic and commercial use. It has interfaces for popular
programming languages, such as C/C++, Python, and Java, and it runs on a variety
of operating systems including Windows, Android, and Unix-like operating systems.

You can explore the OpenCV homepage, www.opencv.org,


for further details.

OpenCV was initially an Intel Research initiative to develop tools to analyze images.

Following is the timeline of OpenCV in brief:

In August 2012, support for OpenCV was taken over by a nonprofit foundation,
OpenCV.org, which is currently developing it further. It also maintains a developer
and user site for OpenCV.

At the time of writing this book, the stable version of


OpenCV was 2.4.10. Version 3.0 Beta is also available.

[3]
Introduction to Computer Vision and Raspberry Pi

Single-board computers and the


Raspberry Pi
A single-board computer system is a complete computer on a single board. The
board includes processor(s), RAM, I/O, and networking ports for interfacing devices.
Unlike traditional computer systems, single-board computers are not modular and
its hardware cannot be upgraded as it's integrated on the board itself. Single-board
computers are used as low-cost computers in academic and research settings. The
use of single-board computers in embedded systems is very prevalent, and many
individuals and organizations have developed and released fully functional products
based on single-board computers.

Popular single-board computers available in the market include, but are not limited
to, Raspberry Pi, Banana Pi, BeagleBone, and Cubieboard.

Raspberry Pi
Raspberry Pi is a series of low-cost, palm-sized, single-board computers developed
by the Raspberry Pi Foundation in the UK. The intention behind the creation of
Raspberry Pi was to promote the teaching of basic computer skills in schools, and
the former serves this purpose well. Raspberry Pi has expanded its footprint well
beyond its intended purpose by penetrating into the market of embedded systems
and research.

The homepage of the Raspberry Pi Foundation is:


http://www.raspberrypi.org

Raspberry Pi models—A, A+, B, and B+—are based on SoC (system on a chip)


Broadcom BCM2835, which includes an ARM11 700 MHz CPU (which can be
overclocked). RPi generation 2 uses a quad core ARM Cortex-A7, the first multicore
Raspberry Pi. Raspberry Pi A and B use SD cards for boot and persistent storage,
whereas models A+, B+, and Pi 2 use microSD cards for the same. The models A and
A+ have 256 MB of RAM, B and B+ have 512 MB of RAM, and Pi 2 has 1 GB of RAM.

As of now, there are five major models of Raspberry Pi, which are as follows:

• Model A
• Model A+ (currently in production and available for purchase)
• Model B (available for purchase but not in production)

[4]
Chapter 1

• Model B+ (currently in production and available for purchase)


• Raspberry Pi 2 (currently in production and available for purchase)

Check out the product page of Raspberry Pi at the following location:


http://www.raspberrypi.org/products/

The Raspberry Pi Foundation provides Debian and Arch variants and Linux
ARM distributions for download. Python is the main programming platform and
languages like C, C++, Java, Perl, and Ruby can be used to program Raspberry Pi.

We will use Raspberry Pi B+ for our Computer Vision learning. However, these
examples can also be executed on other Raspberry Pi Models.

The Raspberry Pi B+ specifications are as follows:

Component Specification

CPU 700 MHz ARM1176JZF-S core (ARM11 family, ARM v6 instruction set)
GPU Broadcom VideoCore IV @250 MHz
Memory 512 MB SDRAM (shared with GPU—the limit of memory used by GPU
can be set using raspi-config utility)
USB 2.0 ports 4
Video output HDMI, composite video (PAL and NTSC) via 3.5 mm TRRS jack shared
with audio out (you need to use converters for VGA type displays)
Audio output Analog via 3.5 mm phone jack; digital via HDMI port
Onboard microSD
storage
Networking 10/100 Mbit/s Fast Ethernet, no onboard Wi-Fi or Bluetooth
Power 600 mA (3 W), 5 V via http://en.wikipedia.org/wiki/MicroUSB
or GPIO header (using MicroUSB for power is recommended)

Operating systems
Raspberry Pi primarily uses Unix-like, Linux-kernel-based operating systems,
like the variants of Debian and Fedora.

The Raspberry Pi models A, A+, B, and B+ are based on the ARM11 family chip,
which runs on the ARM v6 instruction set. The ARM v6 instruction set does not
support Ubuntu and Windows.

[5]
Introduction to Computer Vision and Raspberry Pi

However, the recently launched Raspberry Pi 2 is based on ARM Cortex A7, which
is capable of running both Windows 10 and Ubuntu (Snappy Core). The following
operating systems are officially supported by all the models of Raspberry Pi and are
available for download at the download page:

• OpenELEC
• Pidora (Fedora Remix)
• RASPBMC
• RISC OS
• Raspbian—we will use this with a Raspberry Pi B+ throughout this book.

Windows 10 and Ubuntu are supported by only the recently


launched Pi 2.

Raspbian
Raspbian is an unofficial variant of Debian Wheezy armhf (ARM hard float)
that is compiled for hard float code that will run on Raspberry Pi computers.
It is a free operating system based on Debian that is optimized for the Raspberry Pi
hardware. Raspbian is more than a pure OS. It comes with over 35,000 packages
and precompiled software for Raspberry Pi.

To know more about Raspbian, you can visit


http://www.raspbian.org/.

[6]
Chapter 1

Setting up your Raspberry Pi B+


This is the front view of Raspberry Pi B+:

[7]
Introduction to Computer Vision and Raspberry Pi

This is the flipside of Raspberry Pi B+:

We need the following hardware to set up a Pi:

• Raspberry Pi B+
• A micro USB power supply
Considering that we are going for a bit of power-intensive usage for our Pi
B+ (like connecting picamera), a 5V 2A power supply is recommended.
• A standard USB keyboard
• A microSD card and a microSD to SD card converter
We need a microSD card of minimum 4 GB.
• A USB mouse
• A monitor
You can either use an HDMI monitor or a standard VGA monitor.
• A monitor connection cable and a converter
If you are using an HDMI Monitor, then an HDMI cable is sufficient.
If you are using a VGA monitor, then you need to use an HDMI to VGA
converter with a VGA cable. A few special changes should be made to
/boot/config.txt if you're using a VGA monitor, which will be
explained in the next section.
• A Windows computer with a microSD card reader and a wired
Internet connection

[8]
Chapter 1

Preparing your microSD card manually


This is the original way of installing an OS into a microSD card, and many users,
including me, still prefer it. It allows the SD card to be prepared manually before
it is used, and it allows you to have easier access to the configuration files like
/boot/config.txt, which might have to be modified in a few cases before booting
up the system. The default Raspbian image consists of only two partitions—boot
and system. These would fit into a 2 GB card. However, I recommend you to use a
minimum 4 GB card to be on the safe side. Choosing an 8 GB card will be adequate
for most of the applications.

Following are the instructions for the Windows users:

1. Download the installable file of Win32DiskImager that is available at


http://sourceforge.net/projects/win32diskimager/files/latest/
download and then install it.
2. Download the installable version of WinZip that is available at
http://www.winzip.com/prod_down.html%20 and install it.
3. Go to http://www.raspberrypi.org/downloads and download the latest
image of Raspbian. It will be a compressed file in the ZIP format, and it needs
to be extracted.
4. Extract the ZIP file using WinZip. The extracted file will be in the img format.
5. Insert your microSD card into the card reader and plug the card reader into
your computer. Nowadays, many computers have an inbuilt SD card reader.
In this case, you need to insert the microSD card into the microSD to SD card
converter and insert that into your computer's inbuilt card reader.
6. Run the Win32DiskImager.exe file and write the image into your SD card.

[9]
Introduction to Computer Vision and Raspberry Pi

7. If you have an HDMI monitor, then please skip this step. This additional
step is required only if you are planning to use a VGA monitor in place
of an HDMI monitor.

8. Browse the SD card. It will appear as a drive labeled boot in the Windows
file explorer. Open the config.txt file from the explorer. You will have to
edit the file in the following manner to enable a proper display on your
VGA monitor
°° Change #disable_overscan=1 to disable_overscan=1
°° Change #hdmi_force_hotplug=1 to hdmi_force_hotplug=1
°° Change #hdmi_group=1 to hdmi_group=2
°° Change #hdmi_mode=1 to hdmi_mode=16
°° Change #hdmi_drive=2 to hdmi_drive=2
°° Change #config_hdmi_boost=4 to config_hdmi_boost=4

9. Save the file.

By default, the commented options (which have # at the beginning) are disabled.
We will enable these options by uncommenting their respective lines by removing
# at the beginning of these commented lines.

[ 10 ]
Chapter 1

If you are using Linux or Mac OS, then you will find the instructions
to install the OS on your Micro SD card for these operating systems
at https://www.raspberrypi.org/documentation/
installation/installing-images/.

Booting up your Raspberry Pi for the first


time
Let's boot up our Pi for the first time with the microSD card in the following way:

1. Insert the microSD card into the microSD card slot of Pi.
2. Connect the Pi to the HDMI monitor. In case you have connected the VGA
monitor, connect it using the HDMI to VGA converter.
3. Connect the USB mouse and USB keyboard.
4. Connect the Pi to the power supply with a micro USB power cable. Make
sure that the power is switched off at this point.
5. Check all the connections once and then switch on the power supply of Pi.

At this stage, your Pi will start booting up. You will see a green light blinking on the
Pi board. It means that it's working! Now, there are a few more things that you need
to do before you can really start using your Pi. Once it boots up, it will show the
raspi-config menu, as follows:

[ 11 ]
Introduction to Computer Vision and Raspberry Pi

Perform the following steps and reboot the Pi at the end:

You will have to use the arrow keys and the Enter key to select
options in the text-based menu.

1. Use Expand Filesystem.


2. Go to Enable Boot to Desktop/Scratch | Desktop. Log in as pi at the
graphical desktop.

If you do not enable this option, you will be asked for the
username and password every time you boot. The default
username is pi and the password is raspberry. Once you enter
the username and password, the command prompt will appear.
The default shell of Raspbian is bash. You can confirm it by typing
this in the following command:
echo $SHELL

You can always go to the graphical desktop by typing in the startx


command. To use OpenCV with Python, we are required to use the GUI of
Raspbian to display images and video.

3. Navigate to Internationalisation Options | Change Keyboard Layout.


Change it to US (the default is UK).
4. Enable Camera.
5. Navigate to Advanced Options | Memory Split and select 64 MB for GPU.

This option decides how much RAM is used by the Graphic Processor Unit (GPU).
The more the RAM is allocated to the GPU, the more will the processing of intensive
graphics be done. 64 MB is a good value for most graphics-related purposes.

You can always invoke this tool from the command prompt with the following
command and change the settings:
sudo raspi-config

Shutting down and rebooting your Pi safely


In the Raspbian GUI, there are options that allow you to shut down and reboot Pi.
From the command prompt, you can shut down Pi safely by issuing the following
command:
sudo shutdown –h now

[ 12 ]
Chapter 1

An alternative command is as follows:


sudo halt

You can reboot Pi by using the following command:


sudo reboot

Preparing your Pi for computer vision


Now, we have a working Pi running the Raspbian OS. Please make sure that you
have a working wired Internet connection with a reasonable speed for this activity.
Let's prepare Pi for computer vision:

1. Connect your Pi to an Internet modem or router with an Ethernet cable.


2. Run the following command to restart the networking service:
sudo service networking restart

3. Make sure that Raspberry Pi is connected to the Internet by typing in the


following command:
ping –c4 www.google.com

4. Run the following commands in a sequence:


Advanced Package Tool (apt) is the utility that can be used to install and
remove software in Debian and its variants. We need to use it to update the
Pi software.
°° sudo apt-get update

This command synchronizes the package list from the source. Indexes of all
the packages are refreshed. This command must be issued before we issue
the upgrade command.
°° sudo apt-get upgrade

This will install the newest versions of the already installed software.
Obsolete packages/utilities are not removed automatically. If the
software is up to date, then it's left as it is.
°° sudo rpi-update

This command is used to upgrade the firmware. The kernel and firmware
are installed as a Debian package, and hence, we will also get the updates.
These packages are updated infrequently after extensive testing.

[ 13 ]
Introduction to Computer Vision and Raspberry Pi

5. Now, we will need to install a few necessary packages and dependencies for
OpenCV. Following is a list of packages we need to install. You just need to
connect Pi to the Internet and type in sudo apt-get install <package-
name>, where <package-name> is one of following packages:

libopencv-dev libpng3 libdc1394-22-dev


build-essential libpnglite-dev libdc1394-22
libavformat-dev zlib1g-dbg libdc1394-utils
x264 zlib1g libv4l-0
v4l-utils zlib1g-dev libv4l-dev
ffmpeg pngtools libpython2.6
libcv2.3 libtiff4-dev python-dev
libcvaux2.3 libtiff4 python2.6-dev
libhighgui2.3 libtiffxx0c2 libgtk2.0-dev
python-opencv libtiff-tools libpngwriter0-dev
opencv-doc libjpeg8 libpngwriter0c2
libcv-dev libjpeg8-dev libswscale-dev
libcvaux-dev libjpeg8-dbg libjpeg-dev
libhighgui-dev libavcodec-dev libwebp-dev
python-numpy libavcodec53 libpng-dev
python-scipy libavformat53 libtiff5-dev
python-matplotlib libgstreamer0.10-0-dbg libjasper-dev
python-pandas libgstreamer0.10-0 libopenexr-dev
python-nose libgstreamer0.10-dev libgdal-dev
v4l-utils libxine1-ffmpeg python-tk
libgtkglext1-dev libxine-dev python3-dev
libpng12-0 libxine1-bin python3-tk
libpng12-dev libunicap2 python3-numpy
libpng++-dev libunicap2-dev libeigen3-dev

[ 14 ]
Chapter 1

For example, if you want to install x264, you have to type sudo apt-get
install x264. This will install the necessary package. Similarly, you can
install all of the aforementioned packages in like manner. If a package is
already installed on Pi, it will show the following message:
pi@pi02 ~ $ sudo apt-get install x264
Reading package lists... Done
Building dependency tree
Reading state information... Done
x264 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not
upgraded.

In such cases, don't worry. The package you wanted to install has already
been installed, and it is up to date. Just proceed with the installation of all
the other packages in the list one-by-one.

6. Finally, install OpenCV for Python by using the following command:


sudo apt-get install python-opencv

This is the easiest way to install OpenCV for Python. However, there is a
problem with this. Raspbian repositories may not always contain the latest
version of OpenCV. For example, at the time of writing this book, Raspbian
repository contains version 2.4.1, while the latest OpenCV version is 2.4.10.
With respect to Python API, the latest version will always contain much
better support and more functionality.
Another method is to compile OpenCV from the source, which I will not
recommend for beginners as it's a bit complex and it will take a lot of time.

Testing OpenCV installation with Python


It's very easy to code for OpenCV in Python. It requires very few lines of code
compared to C/C++, and powerful libraries like NumPy can be exploited for
multidimensional data structures that are required for image processing.

On a terminal, type python, and then type the following lines:


>>> import cv2
>>> print cv2.__version__

This will show us the version of OpenCV that was installed on Pi, which, in our case
is 2.4.1.

[ 15 ]
Introduction to Computer Vision and Raspberry Pi

NumPy
NumPy is a fundamental package that can be used to scientifically compute with
Python. It is a matrix library for linear algebra. NumPy can also be used as an
efficient multidimensional container of generic data. Arbitrary data types can be
defined and used. NumPy is an extension of the Python programming language.
It adds support for large multidimensional arrays and matrices, along with a large
library of high-level mathematical functions that can be used to operate on these
arrays. We will use NumPy arrays throughout this book to represent images and
carry out complex mathematical operations. NumPy comes with many inbuilt
functions for all of these operations. So, we do not have to worry about basic array
operations. We can directly focus on the concepts and code for computer vision. All
the OpenCV array structures are converted to and from NumPy arrays. So, whatever
operations you perform in NumPy, you can combine NumPy with OpenCV.

We will use NumPy with OpenCV a lot in this book. Let's start with some simple
example programs that will demonstrate the real power of NumPy.

Open Python via the terminal. Try the following examples.

Array creation
Let's see some examples on array creation. The array() method is used very
frequently in this book. There are many ways to create different types of arrays.
We will explore these ways as and when they are needed in this book. Follow
these commands for array creation:
>>> import numpy as np
>>> x=np.array([1,2,3])
>>> x
array([1, 2, 3])

>>> y=arange(10)
>>> y
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

[ 16 ]
Discovering Diverse Content Through
Random Scribd Documents
the longboat, with vessels for water, if any could be found. I desired
his leave to go with them, that I might see the country and make
what discoveries I could. When we came to land we saw no river or
spring, nor any sign of inhabitants. Our men therefore wandered on
the shore to find out some fresh water near the sea, and I walked
alone about a mile on the other side, where I observed the country
all barren and rocky. I now began to be weary, and seeing nothing
to entertain my curiosity, I returned gently down towards the creek;
and the sea being full in my view, I saw our men already got into
the boat and rowing for life to the ship. I was going to holla after
them, although it had been to little purpose, when I observed a
huge creature walking after them in the sea, as fast as he could; he
waded not much deeper than his knees, and took prodigious strides.
But our men had the start of him half a league, and the sea
thereabouts being full of sharp-pointed rocks, the monster was not
able to overtake the boat. This I was afterwards told, for I durst not
stay to see the issue of that adventure, but ran as fast as I could the
way I first went, and then climbed up a steep hill which gave me
some prospect of the country. I found it fully cultivated; but that
which first surprised me was the length of the grass, which, in those
grounds that seemed to be kept for hay, was above twenty feet
high.
I fell into a highroad, for so I took it to be, though it served to the
inhabitants only as a footpath through a field of barley. Here I
walked on for some time, but could see little on either side, it being
now near harvest, and the corn rising at least forty feet. I was an
hour walking to the end of this field, which was fenced in with a
hedge of at least one hundred and twenty feet high, and the trees
so lofty that I could make no computation of their altitude. There
was a stile to pass from this field into the next. It had four steps,
and a stone to cross over when you came to the uppermost. It was
impossible for me to climb this stile, because every step was six feet
high, and the upper stone above twenty. I was endeavoring to find
some gap in the hedge, when I discovered one of the inhabitants in
the next field advancing towards the stile, of the same size with him
whom I saw in the sea pursuing our boat. He appeared as tall as an
ordinary spire steeple, and took about ten yards at every stride, as
near as I could guess. I was struck with the utmost fear and
astonishment, and ran to hide myself in the corn, whence I saw him
at the top of the stile looking back into the next field on the right
hand, and heard him call in a voice many degrees louder than a
speaking trumpet; but the noise was so high in the air, that at first I
certainly thought it was thunder. Whereupon seven monsters like
himself came towards him with reaping hooks in their hands, each
hook about the largeness of six scythes. These people were not so
well clad as the first, whose servants or laborers they seemed to be;
for, upon some words he spoke, they went to reap the corn in the
field where I lay. I kept from them at as great a distance as I could,
but was forced to move with extreme difficulty, for the stalks of the
corn were sometimes not above a foot distant, so that I could hardly
squeeze my body betwixt them. However, I made a shift to go
forward till I came to a part of the field where the corn had been laid
by the rain and wind. Here it was impossible for me to advance a
step; for the stalks were so interwoven that I could not creep
through, and the beards of the fallen ears so strong and pointed that
they pierced through my clothes into my flesh. At the same time I
heard the reapers not above a hundred yards behind me. Being
quite dispirited with toil, and wholly overcome by grief and despair, I
lay down between two ridges, and heartily wished I might there end
my days. I bemoaned my desolate widow and fatherless children. I
lamented my own folly and willfulness in attempting a second
voyage against the advice of all my friends and relations. In this
terrible agitation of mind I could not forbear thinking of Lilliput,
whose inhabitants looked upon me as the greatest prodigy that ever
appeared in the world; where I was able to draw an imperial fleet in
my hand, and perform those other actions which will be recorded
forever in the chronicles of that empire, while posterity shall hardly
believe them, although attested by millions. I reflected what a
mortification it must prove to me to appear as inconsiderable in this
nation as one single Lilliputian would be among us. But this I
conceived was to be the least of my misfortunes; for, as human
creatures are observed to be more savage and cruel in proportion to
their bulk, what could I expect but to be a morsel in the mouth of
the first among these enormous barbarians that should happen to
seize me? Undoubtedly philosophers are in the right when they tell
us that nothing is great or little otherwise than by comparison. It
might have pleased fortune to let the Lilliputians find some nation
where the people were as diminutive with respect to them, as they
were to me. And who knows but that even this prodigious race of
mortals might be equally overmatched in some distant part of the
world, whereof we have yet no discovery? Scared and confounded
as I was, I could not forbear going on with these reflections, when
one of the reapers approaching within ten yards of the ridge where I
lay, made me apprehend that with the next step I should be
squashed to death under his foot, or cut in two with his reaping
hook. And therefore when he was again about to move, I screamed
as loud as fear could make me; whereupon the huge creature trod
short, and looking round about under him for some time, at last
espied me as I lay on the ground. He considered awhile, with the
caution of one who endeavors to lay hold on a small dangerous
animal in such a manner that it shall not be able either to scratch or
to bite him, as I myself have sometimes done with a weasel in
England. At length he ventured to take me up behind, by the middle,
between his forefinger and thumb, and brought me within three
yards of his eyes, that he might behold my shape more perfectly. I
guessed his meaning, and my good fortune gave me so much
presence of mind, that I resolved not to struggle in the least as he
held me in the air above sixty feet from the ground, although he
grievously pinched my sides, for fear I should slip through his
fingers. All I ventured was to raise my eyes towards the sun and
place my hands together in a supplicating posture, and to speak
some words in a humble melancholy tone, suitable to the condition I
then was in; for I apprehended every moment that he would dash
me against the ground, as we usually do any little hateful animal
which we have a mind to destroy. But my good star would have it,
that he appeared pleased with my voice and gestures, and began to
look upon me as a curiosity, much wondering to hear me pronounce
articulate words, although he could not understand them. In the
meantime I was not able to forbear groaning and shedding tears,
and turning my head towards my sides; letting him know, as well as
I could, how cruelly I was hurt by the pressure of his thumb and
finger. He seemed to apprehend my meaning; for, lifting up the
lappet of his coat, he put me gently into it, and immediately ran
along with me to his master, who was a substantial farmer, and the
same person I had first seen in the field.
The farmer having (as I supposed by their talk) received such an
account of me as his servant could give him, took a piece of a small
straw, about the size of a walking staff, and therewith lifted up the
lappets of my coat, which, it seems, he thought to be some kind of
covering that nature had given me. He blew my hair aside to take a
better view of my face. He called his hands about him, and asked
them, as I afterwards learned, whether they had ever seen in the
fields any little creature that resembled me. He then placed me
softly on the ground upon all fours, but I got immediately up, and
walked slowly backwards and forwards, to let those people see I had
no intent to run away. They all sat down in a circle about me, the
better to observe my motions. I pulled off my hat, and made a low
bow towards the farmer. I fell on my knees, and lifted up my hands
and eyes, and spoke several words as loud as I could. I took a purse
of gold out of my pocket, and humbly presented it to him. He
received it on the palm of his hand, then applied it close to his eye
to see what it was, and afterwards turned it several times with the
point of a pin (which he took out of his sleeve), but could make
nothing of it. Whereupon I made a sign that he should place his
hand on the ground. I then took the purse, and opening it, poured
all the gold into his palm. There were six Spanish pieces of four
pistoles each, besides twenty or thirty smaller coins. I saw him wet
the tip of his little finger upon his tongue, and take up one of my
largest pieces, and then another, but he seemed to be wholly
ignorant what they were. He made me a sign to put them again into
my purse, and the purse again into my pocket, which after offering it
to him several times, I thought it best to do.
The farmer by this time was convinced I must be a rational
creature. He spoke often to me, but the sound of his voice pierced
my ears like that of a watermill, yet his words were articulate
enough. I answered as loud as I could in several languages, and he
often laid his ear within two yards of me, but all in vain, for we were
wholly unintelligible to each other. He then sent his servants to their
work, and taking his handkerchief out of his pocket, he doubled and
spread it on his left hand, which he placed flat on the ground with
the palm upwards, making me a sign to step into it, as I could easily
do, for it was not above a foot in thickness. I thought it my part to
obey, and, for fear of falling, laid myself at full length upon the
handkerchief, with the remainder of which he lapped me up to the
head for further security, and in this manner carried me home to his
house. There he called his wife, and showed me to her; but she
screamed and ran back, as women in England do at the sight of a
toad or a spider. However, when she had awhile seen my behavior,
and how well I observed the signs her husband made, she was soon
reconciled, and by degrees grew extremely tender of me.
It was about twelve at noon and a servant brought in dinner. It
was only one substantial dish of meat (fit for the plain condition of a
husbandman), in a dish of about four-and-twenty feet diameter. The
company were the farmer and his wife, three children, and an old
grandmother. When they were sat down, the farmer placed me at
some distance from him on the table, which was thirty feet high
from the floor. I was in a terrible fright, and kept as far as I could
from the edge for fear of falling. The wife minced a bit of meat, then
crumbled some bread on a trencher, and placed it before me. I made
her a low bow, took out my knife and fork, and fell to eat, which
gave them exceeding delight. The mistress sent her maid for a small
dram cup, which held about three gallons, and filled it with drink; I
took up the vessel with much difficulty in both hands, and in a most
respectful manner drank to her ladyship’s health, expressing the
words as loud as I could in English, which made the company laugh
so heartily that I was almost deafened with the noise. This liquor
tasted like a small cider, and was not unpleasant. Then the master
made me a sign to come to his trencher side; but as I walked on the
table, being in great surprise all the time, as the indulgent reader
will easily conceive and excuse, I happened to stumble against a
crust, and fell flat on my face, but received no hurt. I got up
immediately, and observing the good people to be in much concern,
I took my hat (which I held under my arm out of good manners),
and waving it over my head, gave three huzzas, to show I had got
no mischief by my fall. But advancing forwards towards my master
(as I shall henceforth call him), his youngest son, who sat next to
him, an arch boy of about ten years old, took me up by the legs, and
held me so high in the air that I trembled in every limb; but his
father snatched me from him, and at the same time gave him such a
box on the left ear as would have felled a European troop of horse
to the earth, ordering him to be taken from the table. But being
afraid the boy might owe me a spite, and well remembering how
mischievous all children among us naturally are to sparrows, rabbits,
young kittens, and puppy dogs, I fell on my knees, and pointing to
the boy, made my master to understand as well as I could, that I
desired his son might be pardoned. The father complied, and the lad
took his seat again, whereupon I went to him and kissed his hand,
which my master took, and made him stroke me gently with it.
In the midst of dinner, my mistress’s favorite cat leaped into her
lap. I heard a noise behind me like that of a dozen stocking weavers
at work; and turning my head, I found it proceeded from the purring
of this animal, who seemed to be three times larger than an ox, as I
computed by the view of her head, and one of her paws, while her
mistress was feeding and stroking her. The fierceness of this
creature’s countenance altogether discomposed me, though I stood
at the further end of the table, above fifty feet off; and though my
mistress held her fast, for fear she might give a spring, and seize me
in her talons. But it happened there was no danger, for the cat took
not the least notice of me when my master placed me within three
yards of her. And as I have been always told, and found true by
experience in my travels, that flying, or discovering fear, before a
fierce animal is a certain way to make it pursue or attack you; so I
resolved, in this dangerous juncture, to show no manner of concern.
I walked with intrepidity five or six times before the very head of the
cat, and came within half a yard of her; whereupon she drew herself
back, as if she were more afraid of me. I had less apprehension
concerning the dogs, whereof three or four came into the room, as it
is usual in farmers’ houses; one of which was a mastiff equal in bulk
to four elephants, and a grey-hound somewhat taller than the
mastiff, but not so large.
When dinner was almost done, the nurse came in with a child of a
year old in her arms, who immediately spied me, and began a squall
that you might have heard from London Bridge to Chelsea, after the
usual oratory of infants, to get me for a plaything. The mother, out
of pure indulgence, took me up, and put me towards the child, who
presently seized me by the middle, and got my head in his mouth,
where I roared so loud that the urchin was frighted, and let me
drop; and I should infallibly have broke my neck, if the mother had
not held her apron under me. The nurse, to quiet her babe, made
use of a rattle, which was a kind of hollow vessel filled with great
stones, and fastened by a cable to the child’s waist; but all in vain,
so that she was forced to apply the last remedy by giving it suck. I
must confess no object ever disgusted me so much as the sight of
her monstrous breast, which I cannot tell what to compare with, so
as to give the curious reader an idea of its bulk, shape, and color. I
had a near sight of her, she sitting down the more conveniently to
give suck, and I standing on the table. This made me reflect upon
the fair skins of our English ladies, who appear so beautiful to us
only because they are of our own size, and their defects not to be
seen but through a magnifying glass; where we find by experiment
that the smoothest and whitest skins look rough and coarse, and ill
colored.
I remember when I was at Lilliput, the complexions of those
diminutive people appeared to me the fairest in the world; and
talking upon this subject with a person of learning there, who was
an intimate friend of mine, he said that my face appeared much
fairer and smoother when he looked on me from the ground, than it
did upon a nearer view when I took him up in my hand and brought
him close, which he confessed was at first a very shocking sight. He
said he could discover great holes in my skin; that the stumps of my
beard were ten times stronger than the bristles of a boar, and my
complexion made up of several colors, altogether disagreeable.
Although I must beg leave to say for myself, that I am as fair as
most of my sex and country, and very little sunburned by all my
travels. On the other side, discoursing of the ladies in that emperor’s
court, he used to tell me one had freckles, another too wide a
mouth, a third too large a nose; nothing of which I was able to
distinguish. I confess this reflection was obvious enough; which,
however, I could not forbear, lest the reader might think those vast
creatures were actually deformed: for I must do them the justice to
say they are a comely race of people; and particularly the features of
my master’s countenance, although he were but a farmer, when I
beheld him from the height of sixty feet, appeared very well
proportioned.
“These horrible animals had the boldness to attack me on both
sides”

Page 98

When dinner was done, my master went out to his laborers, and
as I could discover by his voice and gesture, gave his wife a strict
charge to take care of me. I was very much tired and disposed to
sleep, which my mistress perceiving, she put me on her own bed,
and covered me with a clean white handkerchief, but larger and
coarser than the mainsail of a man of war.
I slept about two hours, and dreamed I was at home with my wife
and children, which aggravated my sorrows when I awaked and
found myself alone in a vast room, between two and three hundred
feet wide, and above two hundred high, lying in a bed twenty yards
wide. My mistress was gone about her household affairs, and had
locked me in. The bed was eight yards from the floor. While I was
under these circumstances, two rats crept up the curtains, and ran
smelling backwards and forwards on the bed. One of them came up
almost to my face, whereupon I rose in a fright, and drew out my
hanger to defend myself. These horrible animals had the boldness to
attack me on both sides, and one of them held his forefeet at my
collar; but I had the good fortune to rip up his belly before he could
do me any mischief. He fell down at my feet, and the other, seeing
the fate of his comrade, made his escape, but not without one good
wound on the back, which I gave him as he fled, and made the
blood run trickling from him. After this exploit I walked gently to and
fro on the bed, to recover my breath and loss of spirits. These
creatures were of the size of a large mastiff, but infinitely more
nimble and fierce; so that if I had taken off my belt before I went to
sleep, I must have infallibly been torn to pieces and devoured. I
measured the tail of the dead rat, and found it to be two yards long,
wanting an inch; but it went against my stomach to drag the carcass
off the bed, where it lay still bleeding. I observed it had yet some
life, but with a strong slash across the neck I thoroughly dispatched
it.
Soon after, my mistress came into the room, who seeing me all
bloody, ran and took me up in her hand. I pointed to the dead rat,
smiling and making other signs to show I was not hurt, whereat she
was extremely rejoiced, calling the maid to take up the dead rat with
a pair of tongs, and throw it out of the window. Then she set me on
a table, where I showed her my hanger all bloody, and wiping it on
the lappet of my coat returned it to the scabbard.
I hope the gentle reader will excuse me for dwelling on
particulars, which, however insignificant they may appear to
groveling vulgar minds, yet will certainly help a philosopher to
enlarge his thoughts and imagination, and apply them to the benefit
of public as well as private life, which was my sole design in
presenting this and other accounts of my travels to the world;
wherein I have been chiefly studious of truth, without affecting any
ornaments of learning or of style. But the whole scene of this voyage
made so strong an impression on my mind, and is so deeply fixed in
my memory, that in committing it to paper I did not omit one
material circumstance; however, upon a strict review, I blotted out
several passages of less moment which were in my first copy, for
fear of being censured as tedious and trifling, whereof travelers are
often, perhaps not without justice, accused.
CHAPTER II
A DESCRIPTION OF THE FARMER’S DAUGHTER—THE AUTHOR CARRIED
TO A MARKET TOWN, AND THEN TO THE METROPOLIS—THE
PARTICULARS OF HIS JOURNEY.

My mistress had a daughter of nine years old, a child of forward


parts for her age, very dexterous at her needle, and skillful in
dressing her baby. Her mother and she contrived to fit up the baby’s
cradle for me against night. The cradle was put into a small drawer
of a cabinet, and the drawer placed upon a hanging shelf for fear of
the rats. This was my bed all the time I stayed with those people,
though made more convenient by degrees, as I began to learn their
language and make my wants known. This young girl was so handy,
that after I had once or twice pulled off my clothes before her, she
was able to dress and undress me, though I never gave her that
trouble when she would let me do either myself. She made me
seven shirts, and some other linen, of as fine cloth as could be got,
which indeed was coarser than sackcloth; and these she constantly
washed for me with her own hands. She was likewise my school-
mistress, to teach me the language; when I pointed to anything, she
told me the name of it in her own tongue, so that in a few days I
was able to call for whatever I had a mind to. She was very good-
natured, and not above forty feet high, being little for her age. She
gave me the name of Grildrig, which the family took up, and
afterwards the whole kingdom. The word imports what the Latins
call nanunculus, the Italians homunceletino, and the English
mannikin. To her I chiefly owe my preservation in that country; we
never parted while I was there; I called her my Glumdalclitch, or
little nurse; and I should be guilty of great ingratitude if I omitted
this honorable mention of her care and affection towards me, which
I heartily wish it lay in my power to requite as she deserves, instead
of being the innocent but unhappy instrument of her disgrace, as I
have too much reason to fear.
It now began to be known and talked of in the neighborhood, that
my master had found a strange animal in the field, about the
bigness of a splacknuck, but exactly shaped in every part like a
human creature; which it likewise imitated in all its actions; seemed
to speak in a little language of its own, had already learned several
words of theirs, went erect upon two legs, was tame and gentle,
would come when it was called, do whatever it was bid, had the
finest limbs in the world, and a complexion fairer than a nobleman’s
daughter of three years old. Another farmer, who lived hard by, and
was a particular friend of my master, came on a visit on purpose to
inquire into the truth of this story. I was immediately produced and
placed upon a table, where I walked as I was commanded, drew my
hanger, put it up again, made my reverence to my master’s guest,
asked him in his own language how he did, and told him he was
welcome, just as my little nurse had instructed me. This man, who
was old and dim-sighted, put on his spectacles to behold me better;
at which I could not forbear laughing very heartily, for his eyes
appeared like the full moon shining into a chamber at two windows.
Our people, who discovered the cause of my mirth, bore me
company in laughing, at which the old fellow was fool enough to be
angry and out of countenance. He had the character of a great
miser; and, to my misfortune, he well deserved it by the cursed
advice he gave my master to show me as a sight upon a market day
in the next town, which was half an hour’s riding, about two-and-
twenty miles from our house. I guessed there was some mischief
contriving, when I observed my master and his friend whispering
long together, sometimes pointing at me; and my fears made me
fancy that I overheard and understood some of their words. But the
next morning Glumdalclitch, my little nurse, told me the whole
matter, which she had cunningly picked out from her mother. The
poor girl laid me on her bosom, and fell a-weeping with shame and
grief. She apprehended some mischief would happen to me from
rude vulgar folks, who might squeeze me to death or break one of
my limbs by taking me in their hands. She had also observed how
modest I was in my nature, how nicely I regarded my honor, and
what an indignity I should conceive it to be exposed for money as a
public spectacle to the meanest of the people. She said, her papa
and mamma had promised that Grildrig should be hers; but now she
found they meant to serve her as they did last year, when they
pretended to give her a lamb, and yet, as soon as it was fat, sold it
to a butcher. For my own part, I may truly affirm that I was less
concerned than my nurse. I had a strong hope which never left me,
that I should one day recover my liberty; and as to the ignominy of
being carried about for a monster, I considered myself to be a
perfect stranger in the country, and that such a misfortune could
never be charged upon me as a reproach if ever I should return to
England; since the king of Great Britain himself, in my condition,
must have undergone the same distress.
My master, pursuant to the advice of his friend, carried me in a
box the next market day to the neighboring town, and took along
with him his little daughter, my nurse, upon a pillion behind him. The
box was close on every side, with a little door for me to go in and
out, and a few gimlet holes to let in air. The girl had been so careful
as to put the quilt of her baby’s bed into it for me to lie down on.
However, I was terribly shaken and discomposed in this journey,
though it were but of half an hour; for the horse went about forty
feet at every step, and trotted so high, that the agitation was equal
to the rising and falling of a ship in a great storm, but much more
frequent. Our journey was somewhat further than from London to
St. Albans. My master alighted at an inn which he used to frequent;
and after consulting awhile with the innkeeper, and making some
necessary preparations, he hired the grultrud, or crier, to give notice
through the town of a strange creature to be seen at the sign of the
Green Eagle, not so big as a splacknuck (an animal in that country
very finely shaped, about six feet long), and in every part of the
body resembling a human creature, could speak several words, and
perform a hundred diverting tricks.
I was placed upon a table in the largest room of the inn, which
might be near three hundred feet square. My little nurse stood on a
low stool close to the table, to take care of me, and direct what I
should do. My master, to avoid a crowd, would suffer only thirty
people at a time to see me. I walked about on the table as the girl
commanded; she asked me questions as far as she knew my
understanding of the language reached, and I answered them as
loud as I could. I turned about several times to the company, paid
my humble respects, said they were welcome, and used some other
speeches I had been taught. I took up a thimble filled with liquor,
which Glumdalclitch had given me for a cup, and drank their health.
I drew out my hanger, and flourished with it after the manner of
fencers in England. My nurse gave me part of a straw, which I
exercised as a pike, having learned the art in my youth. I was that
day shown to twelve sets of company, and as often forced to go over
again with the same fopperies, till I was half dead with weariness
and vexation; for those who had seen me made such wonderful
reports, that the people were ready to break down the doors to
come in. My master, for his own interest, would not suffer any one
to touch me except my nurse; and to prevent danger, benches were
set round the table at such a distance as to put me out of
everybody’s reach. However, an unlucky schoolboy aimed a hazelnut
directly at my head, which very narrowly missed me; otherwise it
came with so much violence that it would have infallibly knocked out
my brains, for it was almost as large as a small pumpkin; but I had
the satisfaction to see the young rogue well beaten, and turned out
of the room.
My master gave public notice that he would show me again the
next market day; and in the meantime he prepared a more
convenient vehicle for me, which he had reason enough to do; for I
was so tired with my first journey, and with entertaining company for
eight hours together, that I could hardly stand upon my legs, or
speak a word. It was at least three days before I recovered my
strength; and that I might have no rest at home, all the neighboring
gentlemen from a hundred miles round, hearing of my fame, came
to see me at my master’s own house. There could not be fewer than
thirty persons with their wives and children (for the country is very
populous); and my master demanded the rate of a full room
whenever he showed me at home, although it were only to a single
family; so that for some time I had but little ease every day of the
week (except Wednesday, which is their Sabbath), although I were
not carried to the town.
My master, finding how profitable I was like to be, resolved to
carry me to the most considerable cities of the kingdom. Having
therefore provided himself with all things necessary for a long
journey, and settled his affairs at home, he took leave of his wife,
and upon the 17th of August, 1703, about two months after my
arrival, we set out for the metropolis, situated near the middle of
that empire, and about three thousand miles’ distance from our
house. My master made his daughter Glumdalclitch ride behind him.
She carried me on her lap in a box tied about her waist. The girl had
lined it on all sides with the softest cloth she could get, well quilted
underneath, furnished it with her baby’s bed, provided me with linen
and other necessaries, and made everything as convenient as she
could. We had no other company but a boy of the house, who rode
after us with the luggage.
My master’s design was to show me in all the towns by the way,
and to step out of the road, for fifty or a hundred miles, to any
village or person of quality’s house where he might expect custom.
We made easy journeys, of not above seven or eight score miles a
day; for Glumdalclitch, on purpose to spare me, complained she was
tired with the trotting of the horse. She often took me out of my box
at my own desire, to give me air, and show me the country, but
always held me fast by a leading string. We passed over five or six
rivers many degrees broader and deeper than the Nile or the
Ganges; and there was hardly a rivulet so small as the Thames at
London Bridge. We were ten weeks in our journey, and I was shown
in eighteen large towns, besides many villages and private families.
On the 26th day of October we arrived at the metropolis, called in
their language Lorbrulgrud, or Pride of the Universe. My master took
a lodging in the principal street of the city, not far from the royal
palace, and put out bills in the usual form, containing an exact
description of my person and parts. He hired a large room between
three and four hundred feet wide. He provided a table sixty feet in
diameter, upon which I was to act my part, and palisadoed round
three feet from the edge, and as many high, to prevent my falling
over. I was shown ten times a day, to the wonder and satisfaction of
all people. I could now speak the language tolerably well, and
perfectly understood every word that was spoken to me. Besides, I
had learned their alphabet, and could make a shift to explain a
sentence here and there; for Glumdalclitch had been my instructor
while we were at home, and at leisure hours during our journey. She
carried a little book in her pocket, not much larger than a Sanson’s
Atlas; it was a common treatise for the use of young girls, giving a
short account of their religion; out of this she taught me my letters,
and interpreted the words.
CHAPTER III
THE AUTHOR SENT FOR TO COURT—THE QUEEN BUYS HIM OF HIS
MASTER, THE FARMER, AND PRESENTS HIM TO THE KING—HE
DISPUTES WITH HIS MAJESTY’S GREAT SCHOLARS—AN APARTMENT
AT COURT PROVIDED FOR THE AUTHOR—HE IS IN HIGH FAVOR
WITH THE QUEEN—HE STANDS UP FOR THE HONOR OF HIS OWN
COUNTRY—HIS QUARRELS WITH THE QUEEN’S DWARF.

The frequent labors I underwent every day made in a few weeks a


very considerable change in my health. The more my master got by
me, the more insatiable he grew. I had quite lost my stomach, and
was almost reduced to a skeleton. The farmer observed it, and
concluding I must soon die, resolved to make as good a hand of me
as he could. While he was thus reasoning and resolving with himself,
a slardral, or gentleman usher, came from court, commanding my
master to carry me immediately thither for the diversion of the
queen and her ladies. Some of the latter had already been to see
me, and reported strange things of my beauty, behavior, and good
sense. Her majesty and those who attended her were beyond
measure delighted with my demeanor. I fell on my knees, and
begged the honor of kissing her imperial foot; but this gracious
princess held out her little finger towards me (after I was set on a
table) which I embraced in both my arms, and put the tip of it with
the utmost respect to my lip. She made me some general questions
about my country and my travels, which I answered as distinctly and
in as few words as I could. She asked whether I would be content to
live at court. I bowed down to the board of the table, and humbly
answered that I was my master’s slave, but if I were at my own
disposal, I should be proud to devote my life to her majesty’s
service. She then asked my master whether he were willing to sell
me at a good price. He, who apprehended I could not live a month,
was ready enough to part with me, and demanded a thousand
pieces of gold, which were ordered him on the spot, each piece
being about the bigness of eight hundred moidores; but allowing for
the proportion of all things between that country and Europe, and
the high price of gold among them, was hardly so great a sum as a
thousand guineas would be in England. I then said to the queen,
since I was now her majesty’s most humble creature and vassal, I
must beg the favor that Glumdalclitch, who had always tended me
with so much care and kindness, and understood to do it so well,
might be admitted into her service, and continue to be my nurse and
instructor. Her majesty agreed to my petition, and easily got the
farmer’s consent, who was glad enough to have his daughter
preferred at court; and the poor girl herself was not able to hide her
joy. My late master withdrew, bidding me farewell, and saying he
had left me in a good service; to which I replied not a word, only
making him a slight bow.
The queen observed my coldness, and, when the farmer was gone
out of the apartment, asked me the reason. I made bold to tell her
majesty that I owed no other obligation to my late master than his
not dashing out the brains of a poor harmless creature found by
chance in his field, which obligation was amply recompensed by the
gain he had made in showing me through half the kingdom, and the
price he had now sold me for. That the life I had since led was
laborious enough to kill an animal of ten times my strength. That my
health was much impaired by the continual drudgery of entertaining
the rabble every hour of the day; and that if my master had not
thought my life in danger, her majesty, perhaps, would not have got
so cheap a bargain. But as I was out of all fear of being ill treated,
under the protection of so great and good an empress, the
ornament of nature, the darling of the world, the delight of her
subjects, the phœnix of the creation; so I hoped my late master’s
apprehensions would appear to be groundless, for I already found
my spirits to revive by the influence of her most august presence.
This was the sum of my speech, delivered with great improprieties
and hesitation. The latter part was altogether framed in the style
peculiar to that people, whereof I learned some phrases from
Glumdalclitch, while she was carrying me to court.
The queen, giving great allowance for my defectiveness in
speaking, was, however, surprised at so much wit and good sense in
so diminutive an animal. She took me in her own hand, and carried
me to the king, who was then retired to his cabinet. His majesty, a
prince of much gravity and austere countenance, not well observing
my shape at first view, asked the queen, after a cold manner, how
long it was since she grew fond of a splacknuck; for such it seems
he took me to be, as I lay upon my breast in her majesty’s right
hand. But this princess, who has an infinite deal of wit and humor,
set me gently on my feet upon the scrutoire, and commanded me to
give his majesty an account of myself, which I did in a very few
words; and Glumdalclitch, who attended at the cabinet door, and
could not endure I should be out of her sight, being admitted,
confirmed all that had passed from my arrival at her father’s house.
The king, although he be as learned a person as any in his
dominions, and had been educated in the study of philosophy, and
particularly mathematics; yet when he observed my shape exactly,
and saw me walk erect, before I began to speak conceived I might
be a piece of clockwork (which is in that country arrived to a very
great perfection) contrived by some ingenious artist. But when he
heard my voice and found what I delivered to be regular and
rational, he could not conceal his astonishment. He was by no
means satisfied with the relation I gave him of the manner I came
into his kingdom, but thought it a story concerted between
Glumdalclitch and her father, who had taught me a set of words to
make me sell at a higher price. Upon this imagination he put several
other questions to me, and still received rational answers, no
otherwise defective than by a foreign accent, and an imperfect
knowledge in the language, with some rustic phrases which I had
learned at the farmer’s house, and did not suit the polite style of a
court.
His majesty sent for three great scholars who were then in their
weekly waiting, according to the custom of that country. These
gentlemen, after they had awhile examined my shape with much
nicety, were of different opinions concerning me. They all agreed
that I could not be produced according to the regular laws of nature,
because I was not framed with a capacity of preserving my life,
either by swiftness, or climbing of trees, or digging holes in the
earth. They observed by my teeth, which they viewed with great
exactness, that I was a carnivorous animal; yet most quadrupeds
being an overmatch for me, and field mice, with some others, too
nimble, they could not imagine how I should be able to support
myself, unless I fed upon snails and other insects, which they
offered, by many learned arguments, to evince that I could not
possibly do. One of these virtuosi seemed to think that I might be an
embryo, or abortive birth. But this opinion was rejected by the other
two, who observed my limbs to be perfect and finished, and that I
had lived several years, as it was manifested from my beard, the
stumps whereof they plainly discovered through a magnifying glass.
They would not allow me to be a dwarf, because my littleness was
beyond all degrees of comparison; for the queen’s favorite dwarf, the
smallest ever known in that kingdom, was near thirty feet high. After
much debate, they concluded unanimously that I was only relplum
scalcath, which is, interpreted literally, lusus naturæ; a determination
exactly agreeable to the modern philosophy of Europe, whose
professors, disdaining the old evasion of occult causes, whereby the
followers of Aristotle endeavor in vain to disguise their ignorance,
have invented this wonderful solution of all difficulties, to the
unspeakable advancement of human knowledge.
After this decisive conclusion, I entreated to be heard a word or
two. I applied myself to the king, and assured his majesty that I
came from a country which abounded with several millions of both
sexes, and of my own stature; where the animals, trees, and houses
were all in proportion, and where, by consequence, I might be as
able to defend myself, and to find sustenance, as any of his
majesty’s subjects could do here; which I took for a full answer to
those gentlemen’s arguments. To this they only replied with a smile
of contempt, saying that the farmer had instructed me very well in
my lesson. The king, who had a much better understanding,
dismissing his learned men, sent for the farmer, who by good
fortune was not yet gone out of town. Having therefore first
examined him privately, and then confronted him with me and the
young girl, his majesty began to think that what we told him might
possibly be true. He desired the queen to order that a particular care
should be taken of me; and was of opinion that Glumdalclitch should
still continue in her office of tending me, because he observed we
had a great affection for each other. A convenient apartment was
provided for her at court; she had a sort of governess appointed to
take care of her education, a maid to dress her, and two other
servants for menial offices; but the care of me was wholly
appropriated to herself. The queen commanded her own
cabinetmaker to contrive a box that might serve me for a
bedchamber, after the model that Glumdalclitch and I should agree
upon. This man was a most ingenious artist, and according to my
directions, in three weeks finished for me a wooden chamber of
sixteen feet square, and twelve high, with sash windows, a door, and
two closets, like a London bedchamber. The board that made the
ceiling was to be lifted up and down by two hinges, to put in a bed
ready furnished by her majesty’s upholsterer, which Glumdalclitch
took out every day to air, made it with her own hands, and letting it
down at night, locked up the roof over me. A nice workman, who
was famous for little curiosities, undertook to make me two chairs,
with backs and frames, of a substance not unlike ivory, and two
tables, with a cabinet to put my things in. The room was quilted on
all sides, as well as the floor and the ceiling, to prevent any accident
from the carelessness of those who carried me, and to break the
force of a jolt when I went in a coach. I desired a lock for my door,
to prevent rats and mice from coming in. The smith, after several
attempts, made the smallest that ever was seen among them, for I
have known a larger at the gate of a gentleman’s house in England.
I made a shift to keep the key in a pocket of my own, fearing
Glumdalclitch might lose it. The queen likewise ordered the thinnest
silks that could be gotten, to make me clothes, not much thicker
than an English blanket, very cumbersome till I was accustomed to
them. They were after the fashion of the kingdom, partly resembling
the Persian, and partly the Chinese, and are a very grave decent
habit.
The queen became so fond of my company that she could not
dine without me. I had a table placed upon the same at which her
majesty ate, just at her left elbow, and a chair to sit on.
Glumdalclitch stood on a stool on the floor, near my table, to assist
and take care of me. I had an entire set of silver dishes and plates,
and other necessaries, which in proportion to those of the queen,
were not much bigger than what I have seen of the same kind in a
London toy-shop, for the furniture of a baby-house; these my little
nurse kept in her pocket in a silver box, and gave me at meals as I
wanted them, always cleaning them herself. No person dined with
the queen but the two princesses royal, the elder sixteen years old,
and the younger at that time thirteen and a month. Her majesty
used to put a bit of meat upon one of my dishes, out of which I
carved for myself; and her diversion was to see me eat in miniature;
for the queen (who had indeed but a weak stomach) took up at one
mouthful as much as a dozen English farmers could eat at a meal,
which to me was for some time a very nauseous sight. She would
crunch the wing of a lark, bones and all, between her teeth,
although it were nine times as large as that of a full-grown turkey;
and put a bit of bread in her mouth, as big as two twelve-penny
loaves. She drank out of a golden cup, above a hogshead at a
draught. Her knives were twice as long as a scythe set straight upon
the handle; the spoons, forks, and other instruments were all in the
same proportion. I remember when Glumdalclitch carried me, out of
curiosity, to see some of the tables at court, where ten or a dozen of
these enormous knives and forks were lifted up together, I thought I
had never till then beheld so terrible a sight.
It is the custom that every Wednesday (which, as I have
observed, is their Sabbath) the king and queen, with the royal issue
of both sexes, dine together in the apartment of his majesty, to
whom I was now become a great favorite; and at these times my
little chair and table were placed at his left hand before one of the
salt-cellars. This prince took a pleasure in conversing with me,
inquiring into the manners, religion, laws, government, and learning
of Europe, wherein I gave him the best account I was able. His
apprehension was so clear and his judgment so exact that he made
very wise reflections and observations upon all I said. But I confess
that after I had been a little too copious in talking of my own
beloved country, of our trade and wars by sea and land, of our
schisms in religion, and parties in the state, the prejudices of his
education prevailed so far that he could not forbear taking me up in
his right hand and stroking me gently with the other, after a hearty
fit of laughing, asked me whether I were a Whig or a Tory. Then
turning to his first minister, who waited behind him with a white
staff, near as tall as the mainmast of the Royal Sovereign, he
observed how contemptible a thing was human grandeur, which
could be mimicked by such diminutive insects as I. “And yet,” said
he, “I dare engage these creatures have their titles and distinctions
of honor; they contrive little nests and burrows, that they call houses
and cities; they make a figure in dress and equipage; they love, they
fight, they dispute, they cheat, they betray.” And thus he continued
on, while my color came and went several times with indignation to
hear our noble country, the mistress of arts and arms, the scourge of
France, the arbitress of Europe, the seat of virtue, piety, honor, and
truth, the pride and envy of the world, so contemptuously treated.
But as I was not in a condition to resent injuries, so upon mature
thoughts I began to doubt whether I were injured or no. For, after
having been accustomed several months to the sight and converse
of this people, and observed every object upon which I cast my eyes
to be of proportionable magnitude, the horror I had at first
conceived from their bulk and aspect was so far worn off that if I
had then beheld a company of English lords and ladies in their finery
and birthday clothes, acting their several parts in the most courtly
manner of strutting, and bowing, and prating, to say the truth, I
should have been strongly tempted to laugh as much at them as the
king and his grandees did at me. Neither, indeed, could I forbear
smiling at myself when the queen used to place me upon her hand
towards a looking-glass, by which both our persons appeared before
me in full view together; and there could nothing be more ridiculous
than the comparison; so that I really began to imagine myself
dwindled many degrees below my usual size.
Nothing angered and mortified me so much as the queen’s dwarf,
who, being of the lowest stature that was ever in that country (for I
verily think he was not full thirty feet high), became so insolent at
seeing a creature so much beneath him, that he would always affect
to swagger and look big as he passed by me in the queen’s
antechamber, while I was standing on some table talking with the
lords or ladies of the court, and he seldom failed of a small word or
two upon my littleness; against which I could only revenge myself by
calling him brother, challenging him to wrestle, and such repartees
as are usual in the mouths of court pages. One day at dinner, this
malicious little cub was so nettled with something I had said to him,
that, raising himself upon the frame of her majesty’s chair, he took
me up by the middle, as I was sitting down, not thinking any harm,
and let me drop into a large silver bowl of cream, and then ran away
as fast as he could. I fell over head and ears, and if I had not been a
good swimmer it might have gone very hard with me; for
Glumdalclitch in that instant happened to be at the other end of the
room, and the queen was in such a fright that she wanted presence
of mind to assist me. But my little nurse ran to my relief, and took
me out, after I had swallowed above a quart of cream. I was put to
bed; however, I received no other damage than the loss of a suit of
clothes, which was utterly spoiled. The dwarf was soundly whipped,
and as a further punishment, forced to drink up the bowl of cream
into which he had thrown me. Neither was he ever restored to favor;
for soon after the queen bestowed him on a lady of high quality, so
that I saw him no more, to my very great satisfaction: for I could not
tell to what extremity such a malicious urchin might have carried his
resentment.
He had before served me a scurvy trick, which set the queen a-
laughing, although at the same time she were heartily vexed, and
would have immediately cashiered him, if I had not been so
generous as to intercede. Her majesty had taken a marrowbone
upon her plate, and, after knocking out the marrow, placed the bone
again on the dish erect, as it stood before; the dwarf, watching his
opportunity, while Glumdalclitch was gone to the sideboard,
mounted upon the stool she stood on to take care of me at meals,
took me up in both hands, and squeezing my legs together, wedged
them into the marrowbone above my waist, where I stuck for some
time, and made a very ridiculous figure. I believe it was near a
minute before any one knew what was become of me, for I thought
it below me to cry out. But, as princes seldom get their meat hot,
my legs were not scalded, only my stockings and breeches in a sad
condition. The dwarf, at my entreaty, had no other punishment than
a sound whipping.
I was frequently rallied by the queen upon account of my
fearfulness; and she used to ask me whether the people of my
country were as great cowards as myself! The occasion was this:
The kingdom is much pestered with flies in summer; and these
odious insects, each of them as big as a Dunstable lark, hardly gave
me any rest while I sat at dinner, with their continual humming and
buzzing about my ears. They would sometimes alight upon my
victuals. Sometimes they would fix upon my nose or forehead,
where they stung me to the quick, smelling very offensively; and I
could easily trace that viscous matter which, our naturalists tell us,
enables those creatures to walk with their feet upwards upon a
ceiling. I had much ado to defend myself against these detestable
animals, and could not forbear starting when they came on my face.
It was the common practice of the dwarf to catch a number of these
insects in his hand, as schoolboys do among us, and let them out
suddenly under my nose, on purpose to frighten me, and divert the
queen. My remedy was to cut them in pieces with my knife as they
flew in the air, wherein my dexterity was much admired.
I remember one morning when Glumdalclitch had set me in my
box upon a window, as she usually did in fair days to give me air (for
I durst not venture to let the box be hung on a nail out of the
window, as we do with cages in England), after I had lifted up one
of my sashes, and sat down at my table to eat a piece of sweet cake
for my breakfast, above twenty wasps, allured by the smell, came
flying into the room, humming louder than the drones of as many
bagpipes. Some of them seized my cake and carried it piecemeal
away; others flew about my head and face, confounding me with the
noise, and putting me in the utmost terror of their stings. However, I
had the courage to rise and draw my hanger, and attack them in the
air. I dispatched four of them, but the rest got away, and I presently
shut my window. These creatures were as large as partridges; I took
out their stings, found them an inch and a half long, and as sharp as
needles. I carefully preserved them all; and having since shown
them, with some other curiosities, in several parts of Europe, upon
my return to England I gave three of them to Gresham College and
kept the fourth for myself.
CHAPTER IV
THE COUNTRY DESCRIBED—A PROPOSAL FOR CORRECTING MODERN
MAPS—THE KING’S PALACE, AND SOME ACCOUNT OF THE
METROPOLIS—THE AUTHOR’S WAY OF TRAVELING—THE CHIEF
TEMPLE DESCRIBED.

I now intend to give the reader a short description of this country,


as far as I traveled in it, which was not above two thousand miles
round Lorbrulgrud, the metropolis. For the queen, whom I always
attended, never went further when she accompanied the king in his
progresses, and there stayed till his majesty returned from viewing
his frontiers. The whole extent of this prince’s dominions reaching
about six thousand miles in length, and from three to five in
breadth; from whence I cannot but conclude that our geographers
of Europe are in a great error, by supposing nothing but sea
between Japan and California; for it was ever my opinion that there
must be a balance of earth to counterpoise the great continent of
Tartary; and therefore they ought to correct their maps and charts
by joining this vast tract of land to the northwest parts of America,
wherein I shall be ready to lend them my assistance.
The kingdom is a peninsula, terminated to the northeast by a
ridge of mountains thirty miles high, which are altogether
impassable, by reason of the volcanoes upon the tops; neither do
the most learned know what sort of mortals inhabit beyond those
mountains, or whether they be inhabited at all. On the three other
sides, it is bounded by the ocean. There is not one seaport in the
whole kingdom; and those parts of the coasts into which the rivers
issue, are so full of pointed rocks, and the sea generally so rough,
that there is no venturing with the smallest of their boats; so that
these people are wholly excluded from any commerce with the rest
of the world. But the large rivers are full of vessels, and abound with
excellent fish; for they seldom get any from the sea, because the
sea fish are of the same size with those in Europe, and consequently
not worth catching; whereby it is manifest, that nature, in the
production of plants and animals of so extraordinary a bulk, is wholly
confined to this continent, of which I leave the reasons to be
determined by philosophers. However, now and then they take a
whale that happens to be dashed against the rocks, which the
common people feed on heartily. These whales I have known so
large, that a man could hardly carry one upon his shoulders; and
sometimes, for curiosity, they are brought in hampers to
Lorbrulgrud; I saw one of them in a dish at the king’s table, which
passed for a rarity, but I did not observe he was fond of it; for I
think, indeed, the bigness disgusted him, although I have seen one
somewhat larger in Greenland.
The country is well inhabited, for it contains fifty-one cities, near a
hundred walled towns, and a great number of villages. To satisfy my
curious reader, it may be sufficient to describe Lorbrulgrud. This city
stands upon almost two equal parts on each side of the river that
passes through. It contains above eighty thousand houses, and
about six hundred thousand inhabitants. It is in length three
glongluns (which make about fifty-four English miles), and two and a
half in breadth, as I measured it myself in the royal map made by
the king’s order, which was laid on the ground on purpose for me,
and extended a hundred feet; I paced the diameter and
circumference several times barefoot, and computing by the scale,
measured it pretty exactly.
The king’s palace is no regular edifice, but a heap of buildings
about seven miles round; the chief rooms are generally two hundred
and forty feet high, and broad and long in proportion. A coach was
allowed to Glumdalclitch and me, wherein her governess frequently
took her out to see the town, or go among the shops; and I was
always of the party, carried in my box; although the girl, at my own
desire, would often take me out, and hold me in her hand, that I
might more conveniently view the houses and the people, as we
passed along the streets. I reckoned our coach to be about a square
of Westminster Hall, but not altogether so high; however, I cannot
be very exact. One day the governess ordered our coachman to stop
at several shops, where the beggars, watching their opportunity,
crowded to the sides of the coach, and gave me the most horrible
spectacles that ever an English eye beheld.
Beside the large box in which I was usually carried, the queen
ordered a smaller one to be made for me, of about twelve feet
square, and ten high, for the convenience of traveling; because the
other was somewhat too large for Glumdalclitch’s lap, and
cumbersome in the coach; it was made by the same artist, whom I
directed in the whole contrivance. This traveling closet was an exact
square, with a window in the middle of three of the squares, and
each window was latticed with iron wire on the outside, to prevent
accidents in long journeys. On the fourth side, which had no
window, two strong staples were fixed, through which the person
that carried me, when I had a mind to be on horseback, put in a
leather belt, and buckled it about his waist. This was always the
office of some grave trusty servant in whom I could confide, whether
I attended the king and queen in their progresses, or were disposed
to see the gardens, or pay a visit to some great lady or minister of
state in the court, when Glumdalclitch happened to be out of order;
for I soon began to be known and esteemed among the greatest
officers, I suppose more upon account of their majesties’ favor than
any merit of my own. In journeys, when I was weary of the coach, a
servant on horseback would buckle my box, and place it on a
cushion before him; and there I had a full prospect of the country on
three sides from my three windows. I had in this closet a field bed,
and a hammock hung from the ceiling, two chairs and a table, neatly
screwed to the floor, to prevent being tossed by the agitation of the
horse or the coach. And having long been used to sea voyages,
those motions, although sometimes very violent, did not much
discompose me.
Whenever I had a mind to see the town, it was always in my
traveling closet, which Glumdalclitch held in her lap in a kind of open
sedan, after the fashion of the country, borne by four men, and
attended by two others in the queen’s livery. The people, who had
often heard of me, were very curious to crowd about the sedan, and

You might also like