# Connexions

You are here: Home » Content » From MATLAB and Simulink to Real-Time with TI DSP's » Finding Shapes in Images

### Lenses

What is a lens?

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

#### Affiliated with (What does "Affiliated with" mean?)

This content is either by members of the organizations listed or about topics related to the organizations listed. Click each link to see a list of all content affiliated with the organization.
• TI DSP

This collection is included inLens: Texas Instruments DSP Lens
By: Texas Instruments

Click the "TI DSP" link to see all content affiliated with them.

Click the tag icon to display tags associated with this content.

#### Also in these lenses

• Lens for Engineering

This module and collection are included inLens: Lens for Engineering
By: Sidney Burrus

Click the "Lens for Engineering" link to see all content selected in this lens.

### Recently Viewed

This feature requires Javascript to be enabled.

### Tags

(What is a tag?)

These tags come from the endorsement, affiliation, and other lenses that include this content.

Inside Collection (Report):

Report by: Jacob Fainguelernt. E-mail the author

# Finding Shapes in Images

Module by: Jacob Fainguelernt. E-mail the author

Summary: In this module, you will use the Hough Transform, Find Local Maxima, and Hough Lines blocks to find the longest line in an image. The algorithm used for line detection will be the basis of a lane detection procedure.

## Introduction

In this section, you will use the Hough Transform, Find Local Maxima, and Hough Lines blocks to find the longest line in an image. In the second step, the algorithm used for line detection will be the basis of a lane detection procedure.

### Hardware and Software Requirements

This laboratory was originally developed using the following hardware and software:

• MATLAB® R2008a
• Code Composer Studio (CCS) v3.3
• Texas Instruments DM6437 hardware.

## Line Detection

In this session we will show how to create the line detection model , and how it can be integrated in Simulation and Real-Time Implementations.

### Simulation

Open the “stills_R_W.mdl” Simulink model (generated in the "A Framework for Image Processing with the DSK6416" module).

Add to it the blocks shown in the following table:

 Block Library Quantity Edge Detection Video and Image Processing Blockset / Analysis & Enhancement 1 Hough Transform Video and Image Processing Blockset / Transforms 1 Find Local Maxima Video and Image Processing Blockset / Statistics 1 Selector Simulink®/ Signal Routing 2 Variable Selector Signal Processing Blockset / Signal Management / Indexing 2 Terminator Simulink / Sinks 1 Hough Lines Video and Image Processing Blockset / Transforms 1 Draw Shapes Video and Image Processing Blockset / Text & Graphics 1

Use the Image From Workspace block to import your image from the MATLAB workspace.

Set the block parameters as follows:

• Main pane, Value = I
• Main pane, Output port labels = I

Use the Edge Detection block to find the edges in the intensity image. This process improves the efficiency of the Hough Lines block as it reduces the image area over which the block searches for lines. The block also converts the image to a binary image, which is the required input for the Hough Transform block. Use the default parameters.

Use the Video Viewer block to display the edges found by the Edge Detection block. Set the Input image type parameter to Intensity.

Use the Hough Transform block to compute the Hough matrix by transforming the input image into the rho-theta parameter space. The block also outputs the rho and theta values associated with the Hough matrix. Set the block parameters as follows:

• Theta resolution (radians) = pi/360
• Select the Output theta and rho values check box.

Use the Find Local Maxima block to find the location of the maximum value in the Hough matrix. Set the block parameters as follows:

• Maximum number of local maxima (N) = 1
• Select the Input is Hough matrix spanning full theta range check box.

Use the Selector blocks to separate the indices of the rho and theta values, which are output at the Idx port, that are associated with the maximum value in the Hough matrix. Set the Selector block parameters as follows:

• Index mode = Zero-based
• Elements (-1 for all elements) = 0
• Input port width = 2

Set the Selector1 block parameters as follows:

• Index mode = Zero-based
• Elements (-1 for all elements) = 1
• Input port width = 2

Use the Variable Selector blocks to index into the rho and theta vectors and determine the rho and theta values that correspond to the longest line in the original image. Set the parameters of the Variable Selector blocks as follows:

• Select = Columns
• Index mode = Zero-based

Use the Hough Lines block to determine where the longest line intersects the edges of the original image. You use these coordinates to superimpose a white line on the original image. Use the default parameters.

Use the Draw Shapes block to draw a white line over the longest line on the original image. Set the block parameters as follows:

• Input image type = Intensity
• Shape = Lines
• Border intensity = White

Use the Video Viewer block to display the original image with a white line superimposed over the longest line in the image. Set the Input image type parameter to Intensity.

Connect the blocks as shown in the figure below. Use the file circuit.tif as input.

Create a Subsystem for the Hough algorithm. Select the blocks as shown in the following picture:

In the main menu, click on Edit/Create Subsystem (you may also enter Ctrl+G), as follows:

Your model should resemble the following figure:

Double-click the "Hough Algorithm", and you should see:

Create a Subsystem for the “Line Drawing and Image Construction”. Select the blocks as shown in the following picture:

In the main menu, click on Edit/Create Subsystem (you may also enter Ctrl+G),

Your model should resemble the following figure:

Double-click the " Line Drawing and Image Construction ", and you should see:

Create a Subsystem for the “Line Detection”. Select the blocks as shown in the following picture:

The model should look as follows:

Save the file as "LineDetection.mdl"

Set the configuration parameters. Open the Configuration dialog box by selecting Configuration Parameters from the Simulation menu. Set the parameters as follows:

• Solver pane, Stop time = 0
• Solver pane, Type = Fixed-step
• Solver pane, Solver = discrete (no continuous states)

The Video Viewer window displays the edges found in the original image in white and the background in black. To view the image at its true size, right-click the window and select Set Display To True Size.

Running this gives you the images in Figure 1.

The Video Viewer1 window displays the original image with a white line drawn over the longest line in the image.

You may repeat the simulation here to experiment the various algorithms with different thresholds.

### Real Time Implementation

Open the “stills_R_W.mdl” Simulink model (generated in the "A Framework for Image Processing with the DSK6416" module).

Copy the "Line Detection" block from "LineDetection.mdl".

Connect the various blocks as shown in . Save the model (LineDetectionPictureDSK6416.mdl).

Build the project. Double-click the “Build Project” block.

Run the target. Double-click the “Run” block.

Plotting the input and output in MATLAB, you will see :

## Lane Detection

In this session we will show how to create the lane detection model, as an extension of the Line Detection Model, introduced in the previous chapter.

### Simulation

Open the “video_sim.mdl” Simulink model (generated in the "A Framework for Video Processing with the DM6437 DVDP" module). Copy the “line Detection” block in this model into the “video_sim.mdl”, and connect it to the I/O blocks as follows:

Double-Click the “Line Detection” block. In the open window, add the “Submatrix block from the Signal Processing Toolbox (EIhter from the “Math Functions / Matrices and Linear Algebra / Matrix Operations” group or from the “Signal Management / Indexing” group. Connect it between the input node and the “Edge Detection Block” as follows:

Configure the “Submatrix” block as follows:

This will define the Region of Interest (ROI). Rename the block to “Define ROI”

Select the “Edge Detection Block”, and create a Subsystem for the “Enhanced Detection”, as shown in the following picture:

The model should look as follows:

Double Click the “Enhanced Edge Detection” block. Rename the Input port to “ROI”, and the output port to “Binary Image”

Add to it the blocks shown in the following table:

 Block Library Quantity 2-D Histogram Video and Image Processing Blockset / Statistics 1 Maximum Signal Processing Blockset/ Statistics 1 Data Type Conversion Simulink/ Signal Attributes 1 Bias Simulink / Math Operations 1 Gain Simulink / Math Operations 1 Relational Operator Simulink / Logic and Bit Operations 1 Logical Operator Simulink / Logic and Bit Operations 1

Place the blocks so that your model resembles the following figure. Create the “Calculated threshold based on histogram” with the selected blocks.

The model should look as shown in the following picture. Create the “Histogram based binary thresholding” with the selected blocks.

Double-click the “Hough Algorithm” block in the model. You should change it to select the two longest lines.

You should change the configuration of the selector blocks as follows:

Add an “Embedded MATLAB function” block (from the “Simulink/User-Defined Functions” group). Double-Click the block and enter the following MATLAB function:


function [Thetas, Rhos] = fcn( thetas,rhos)
% This block supports an embeddable subset of the MATLAB language.
% See the help menu for details.

%initialise a frame count
persistent count;
if isempty(count)
count = 0;
end

%remember previous outputs
persistent lastRhos;
persistent lastThetas;

%initialise to same as first input for first entry into function
if isempty(lastRhos)
lastRhos = rhos;
end
if isempty(lastThetas)
lastThetas = thetas;
end

%Assume that all is OK initially
Rhos = rhos;
Thetas = thetas;

if count == 4
%after the 4th frame, engage the test logic
for I = 1:length(rhos)
if (abs(rhos(I) - lastRhos(I)) > 30) || (abs(thetas(I) - lastThetas(I)) > 10*(pi/180))
%too much change - just use the old values
% outR(I) = lastRhos(I);
% outT(I) = lastThetas(I);
Rhos(I) = lastRhos(I);
Thetas(I) = lastThetas(I);
end
end

else
%otherwise just output the computed values
count = count+1;
end

%assign outputs
%Rhos = outR;
%Thetas = outT;

%remember outputs for next time
lastRhos = Rhos;
lastThetas = Thetas;

Connect the block as shown in the following picture:

In the main model, double-click the “Line Drawing and Image Construction” block.

Change the configuration of the “Draw Lines” block as follows:

Now, it will draw the polygon based on the two longest lines.

Add the following blocks to the subsystem:

 Block Library Quantity Concatenate Simulink /Math Operations 2 Selector Simulink / Signal Routing 3 Gain Simulink / Math Operations 1 Relational Operator Simulink / Logic and Bit Operations 1 Logical Operator Simulink / Logic and Bit Operations 1 Submatrix Signal Processing Toolbox:“Math Functions / Matrices and Linear Algebra / Matrix Operations” or “Signal Management / Indexing” 1

Connect the blocks as follows:

The blocks should be configured as follows:

• Selector5:
• Selector4:
• Selector3:
• Vertices Matrix:
• Draw Lane
• Superposition of Lane and Original Image
• Extraction

Rename the “Line Detection” to “Lane Detection”. Save the model as “LaneDetection.mdl” The model should look as follows:

Double Click the Lane Detection block. You may rename the blocks’ names. It will look as follows:

Running this gives you the images in Figure 7.

### Real Time Implementation using TCP/IP

#### Procedure

Open the “RW_dm6437_tcpip.mdl” Simulink model (generated in the "A Framework for Video Processing with the DM6437 DVDP" module).

Save the model as "lane_dm6437_tcpip.mdl".

Change the name of the “R_W Algorithm” block to “Lane Algorithm”.

Right click on the "Build/Reload & Run" subsystem, choose “Block Properties”. Go to the Callbacks tab, and under OpenFcn* enter: “lane_tcpip_script('lane_pcl_tcpip');”, as shown in the following picture:

Double-click the “Task” block and make the same changes as shown:

Double-Click the “Lane Algorithm” subsystem.

Copy "Lane Detection and Tracking" block from "LaneDetection.mdl" into this model as shown.

Configure the "TCP/IP Receive" block :

Configure the "TCP/IP Send" block :

Configure the "Byte Unpack" block :

Configure the "Byte Pack" block :

Open the "RW_pcl_tcpip.mdl" model, created in the "Video R_W" directory.

Save the model as "lane_pcl_tcpip.mdl".

Double-click the “Video Source” block and make the same changes as shown:

Configure the "TCP/IP Receive" block :

Double-click the “Display” block, Double-click the “Data Unpack” block and Configure the "Byte Unpack" block as shown:


function lane_tcpip_script(hostModelName)
% controls host-side TCP/IP processing for
% Video Surveillance demo:
%********** Initialization ********************
% Get model name
modelName = gcs;

% Connect to CCS
CCS_Obj = connectToCCS(modelName);
saved_visibility = CCS_Obj.isvisible;
CCS_Obj.visible(1);

% Run application
fprintf('Running application: %s\n', modelName);
CCS_Obj.run;

% Allow some time for DHCP address acquisition
pause(3);

% Retrieve target's host name
boardType = get_param([modelName '/IP Config'], 'boardType');
userPrompt = sprintf('Enter the IP address or the host name of the %s board: ', boardType);
hostName = inputdlg(userPrompt, 'Target IP address');
if isempty(hostName)
errordlg('You have to provide a valid IP address or host name to run the demo.',
...'TCP/IP Surveillance Recording', 'modal');
return;
end
hostName = strtrim(hostName{1});

% Launch host side UDP receive / Video display model
fprintf('Launching host side application: %s\n', hostModelName);
open_system(hostModelName);

% Update host side TCP/IP blocks with target's IP address
set_param([hostModelName '/TCP//IP Send'], 'Host', hostName);
fprintf('Click on play button to start running the host side application!\n\n')

%[EOF] tcpip_surveil_script.m 

Open a new m-file, copy the following code and save it as "lane_tcpip_script.m" at the same directory as the model.

### Running the Real-time Model

Build load and run the project from the "lane_dm6437l_tcpip.mdl" model. Double-click the "Build / Reload & Run" block.

Running the script, you will see:

## Content actions

PDF | EPUB (?)

### What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

PDF | EPUB (?)

### What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

#### Collection to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks

#### Module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks