Distributed Image Processing in Cloud Dataproc

Join Sign in

Distributed Image Processing in Cloud Dataproc

1 hour 5 Credits


Google Cloud self-paced labs logo


In this hands-on lab, you will learn how to use Apache Spark on Cloud Dataproc to distribute a computationally intensive image processing task onto a cluster of machines. This lab is part of a series of labs on processing scientific data.

What you'll learn

  • How to create a managed Cloud Dataproc cluster with Apache Spark pre-installed.

  • How to build and run jobs that use external packages that aren't already installed on your cluster.

  • How to shut down your cluster.


This is an advanced level lab. Familiarity with Cloud Dataproc and Apache Spark is recommended, but not required. If you're looking to get up to speed in these services, be sure to check out the following labs:

Once you're ready, scroll down to learn more about the services that you'll be using in this lab.


Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.

  4. Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  5. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Navigation menu icon


Cloud Dataproc is a managed Spark and Hadoop service that lets you take advantage of open source data tools for batch processing, querying, streaming, and machine learning. Cloud Dataproc automation helps you create clusters quickly, manage them easily, and save money by turning clusters off when you don't need them. With less time and money spent on administration, you can focus on your jobs and your data.

Consider using Cloud Dataproc to scale out compute-intensive jobs that meet these characteristics:

  1. The job is embarrassingly parallel —in other words, you can process different subsets of the data on different machines.
  2. You already have Apache Spark code that does the computation or you are familiar with Apache Spark.
  3. The distribution of the work is pretty uniform across your data subsets.

If different subsets require different amounts of processing (or if you don't already know Apache Spark), Apache Beam on Cloud Dataflow is a compelling alternative because it provides autoscaling data pipelines.

In this lab, the job that you will run outlines the faces in the image using a set of image processing rules specified in OpenCV. The Vision API is a better way to do this, since these sort of hand-coded rules don't work all that well, but this lab is an example of doing a compute-intensive job in a distributed way.

Task 1. Create a development machine in Compute Engine

First, you create a virtual machine to host your services.

  1. In the Cloud Console, go to Compute Engine > VM Instances > Create Instance.

The navigation path to the Create Instance button, which is highlighted

  1. Configure the following fields and leave the others at their default value:

    • Name: devhost

    • Series: N1

    • Machine Type: 2 vCPUs (n1-standard-2 instance)

    • Identity and API Access: Allow full access to all Cloud APIs.

    The create instance page displaying the populated fields mentioned in step 2.

  2. Click Create. This will serve as your development ‘bastion' host.

Test completed task

Click Check my progress to verify your performed task. If you have completed the task successfully you will granted with an assessment score.

Create a development machine in Compute Engine.
  1. Now SSH into the instance by clicking the SSH button on the Console.

Task 2. Install software

Now set up the software to run the job. Using sbt, an open source build tool, you'll build the JAR for the job you'll submit to the Cloud Dataproc cluster. This JAR will contain the program and the required packages necessary to run the job. The job will detect faces in a set of image files stored in a Cloud Storage bucket, and write out image files with the faces outlined, to either the same or to another Cloud Storage bucket.

  1. Set up Scala and sbt. In the SSH window, install Scala and sbt with the following commands so that you can compile the code:

sudo apt-get install -y dirmngr unzip sudo apt-get update sudo apt-get install -y apt-transport-https echo "deb all main" | sudo tee /etc/apt/sources.list.d/sbt.list echo "deb /" | sudo tee /etc/apt/sources.list.d/sbt_old.list curl -sL "" | sudo apt-key add sudo apt-get update sudo apt-get install -y bc scala sbt

Now you'll build the Feature Detector files. The code for this lab is a slight modification of a solution which exists in the Cloud Dataproc repository on GitHub. You'll download the code, then cd into the directory for this lab and build a "fat JAR" of the feature detector so that it can be submitted to Cloud Dataproc.

  1. Run the following commands in the SSH window:

sudo apt-get update gsutil cp gs://spls/gsp124/ . unzip cd cloud-dataproc/codelabs/opencv-haarcascade
  1. Launch build. This command builds a "fat JAR" of the Feature Detector so that it can be submitted to Cloud Dataproc:

sbt assembly Note: This step will take a while to process, approximately five or more minutes. Please be patient.

Test completed task

Click Check my progress to verify your performed task. If you have completed the task successfully you will granted with an assessment score.

Install Software in the development machine.

Task 3. Create a Cloud Storage bucket and collect images

Now that you built your Feature Detector files, create a Cloud Storage bucket and add some sample images to it.

  1. Fetch the Project ID to use to name your bucket:

GCP_PROJECT=$(gcloud config get-value core/project)
  1. Name your bucket and set a shell variable to your bucket name. The shell variable will be used in commands to refer to your bucket:

MYBUCKET="${USER//google}-image-${RANDOM}" echo MYBUCKET=${MYBUCKET}
  1. Use the gsutil program, which comes with gcloud in the Cloud SDK, to create the bucket to hold your sample images:

gsutil mb gs://${MYBUCKET}

Test completed task

Click Check my progress to verify your performed task. If you have completed the task successfully you will granted with an assessment score.

Create a Cloud Storage bucket.
  1. Download some sample images into your bucket:

curl | gsutil cp - gs://${MYBUCKET}/imgs/family-of-three.jpg curl | gsutil cp - gs://${MYBUCKET}/imgs/african-woman.jpg curl | gsutil cp - gs://${MYBUCKET}/imgs/classroom.jpg

You just downloaded the following images into your Cloud Storage bucket:

A family of three

A woman

A classroom

Test completed task

Click Check my progress to verify your performed task. If you have completed the task successfully you will granted with an assessment score.

Download some sample images into your bucket.
  1. Run this to see the contents of your bucket:

gsutil ls -R gs://${MYBUCKET}


gs://gcpstaging20392-student-image-23218/imgs/: gs://gcpstaging20392-student-image-23218/imgs/african-woman.jpg gs://gcpstaging20392-student-image-23218/imgs/classroom.jpg gs://gcpstaging20392-student-image-23218/imgs/family-of-three.jpg `

Task 4. Create a Cloud Dataproc cluster

  1. Run the following commands in the SSH window to name your cluster and to set the MYCLUSTER variable. You'll be using the variable in commands to refer to your cluster:

  1. Set a global Compute Engine region to use and create a new cluster:

gcloud config set dataproc/region us-west1 gcloud dataproc clusters create ${MYCLUSTER} --bucket=${MYBUCKET} --worker-machine-type=n1-standard-2 --master-machine-type=n1-standard-2 --initialization-actions=gs://spls/gsp010/ --image-version=2.0
  1. If prompted to use a zone instead of a region, enter Y.

This might take a couple minutes. The default cluster settings, which include two worker nodes, should be sufficient for this lab. n1-standard-2 is specified as both the worker and master machine type to reduce the overall number of cores used by the cluster.

For the initialization-actions flag, you are passing a script which installs the libgtk2.0-dev library on each of your cluster machines. This library will be necessary to run the code.

Note: If your cluster fails to create, try deleting your cluster (gcloud dataproc clusters delete ${MYCLUSTER}) and then retrying the previous cluster creation command.

Test completed task

Click Check my progress to verify your performed task. If you have completed the task successfully you will granted with an assessment score.

Create a Cloud Dataproc cluster. Note: To learn more aboutusing command line flags to customize cluster settings, refer to the Cloud SDK gcloud dataproc clusters create reference.

Task 5. Submit your job to Cloud Dataproc

In this lab the program you're running is used as a face detector, so the inputted haar classifier must describe a face. A haar classifier is an XML file that is used to describe features that the program will detect. You will download the haar classifier file and include its Cloud Storage path in the first argument when you submit your job to your Cloud Dataproc cluster.

  1. Run the following command in the SSH window to load the face detection configuration file into your bucket:

curl | gsutil cp - gs://${MYBUCKET}/haarcascade_frontalface_default.xml
  1. Use the set of images you uploaded into the imgs directory in your Cloud Storage bucket as input to your Feature Detector. You must include the path to that directory as the second argument of your job-submission command.

  • Submit your job to Cloud Dataproc:

cd ~/cloud-dataproc/codelabs/opencv-haarcascade gcloud dataproc jobs submit spark \ --cluster ${MYCLUSTER} \ --jar target/scala-2.12/feature_detector-assembly-1.0.jar -- \ gs://${MYBUCKET}/haarcascade_frontalface_default.xml \ gs://${MYBUCKET}/imgs/ \ gs://${MYBUCKET}/out/

You can add any other images to use to the Cloud Storage bucket specified in the second argument.

  1. Monitor the job, in the Console go to Navigation menu > Dataproc > Jobs.

Move on to the next step when you get a similar output:

The jobs output displays a succeeded status

Test completed task

Click Check my progress to verify your performed task. If you have completed the task successfully you will granted with an assessment score.

Submit your job to Cloud Dataproc.
  1. When the job is complete, go to Navigation menu > Cloud Storage and find the bucket you created (it will have your username followed by student-image followed by a random number) and click on it.

  2. Click on an image in the Out directory.

  3. Click on Download icon, the image will download to your computer.

How accurate is the face detection? The Vision API is a better way to do this, since this sort of hand-coded rules don't work all that well. You can see how it works next.

  1. (Optional) In your bucket go to the imgs folder and click on the other images you uploaded to your bucket. This will download the three sample images. Save them to your computer.

  2. Click on this link to go to the Vision API page, scroll down to the Try the API section and upload the images you downloaded from your bucket. You'll see the results of the image detection in seconds. The underlying machine learning models keep improving, so your results may not be the same:

Face detection on the woman Face detection in the classrom Face detection on the family of three

  1. (Optional) If you want to experiment with improving the Feature Detector, you can make edits to the FeatureDetector code, then re-run sbt assembly and the gcloud dataproc and jobs submit commands.

Task 6. Test your understanding

Below are multiple-choice questions to reinforce your understanding of this lab's concepts. Answer them to the best of your abilities.


You learned how to spin up a Cloud Dataproc cluster and run jobs!

Finish your quest

This self-paced lab is part of the Scientific Data Processing quest. A quest is a series of related labs that form a learning path. Completing this quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in this quest and get immediate completion credit. Refer to the Google Cloud Skills Boost catalog for all available quests.

Take your next lab

Continue your quest with Analyzing Natality Data Using Datalab and BigQuery, or try below one:

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated September 11, 2022

Lab Last Tested July 25, 2021

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.