0% found this document useful (0 votes)
180 views

Automatically Detect and Recognize Text in Natural Images With MATLAB

This document describes an algorithm for automatically detecting and recognizing text in natural images. The algorithm starts with a large number of text region candidates and progressively removes those less likely to contain text. It is applied to images containing a road sign, poster, and license plates to demonstrate its flexibility. The algorithm uses techniques like MSER region detection, Canny edge detection, morphological operations, and analysis of character properties to segment and identify text regions.

Uploaded by

avmap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
180 views

Automatically Detect and Recognize Text in Natural Images With MATLAB

This document describes an algorithm for automatically detecting and recognizing text in natural images. The algorithm starts with a large number of text region candidates and progressively removes those less likely to contain text. It is applied to images containing a road sign, poster, and license plates to demonstrate its flexibility. The algorithm uses techniques like MSER region detection, Canny edge detection, morphological operations, and analysis of character properties to segment and identify text regions.

Uploaded by

avmap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Automatically Detect and Recognize Text in

Natural Images
Open this Example

This example shows how to detect regions containing text in an image. It is a common task
performed on unstructured scenes, for example when capturing video from a moving vehicle for
the purpose of alerting a driver about a road sign. Segmenting out the text from a cluttered scene
greatly helps with additional tasks such as optical character recognition (OCR).
The automated text detection algorithm in this example starts with a large number of text region
candidates and progressively removes those less likely to contain text. To highlight this
algorithm's flexibility, it is applied to images containing a road sign, a poster and a set of license
plates.
Step 1: Load image
Load the image. The text can be rotated in plane, but significant out of plane rotations may
require additional pre-processing.
colorImage = imread('handicapSign.jpg');
figure; imshow(colorImage); title('Original image')

Step 2: Detect MSER Regions


Since text characters usually have consistent color, we begin by finding regions of similar
intensities in the image using the MSER region detector [1].
% Detect and extract regions
grayImage = rgb2gray(colorImage);

mserRegions = detectMSERFeatures(grayImage,'RegionAreaRange',[150 2000]);


mserRegionsPixels = vertcat(cell2mat(mserRegions.PixelList)); % extract regions
% Visualize the MSER regions overlaid on the original image
figure; imshow(colorImage); hold on;
plot(mserRegions, 'showPixelList', true,'showEllipses',false);
title('MSER regions');

Some of these regions include extra background pixels. At this stage, the letter E and D in
"TOWED" combine into one region. Also notice that the space between bricks is included.
Step 3: Use Canny Edge Detector to Further Segment the Text
Since written text is typically placed on clear background, it tends to produce high response to
edge detection. Furthermore, an intersection of MSER regions with the edges is going to produce
regions that are even more likely to belong to text.
% Convert MSER pixel lists to a binary mask
mserMask = false(size(grayImage));
ind = sub2ind(size(mserMask), mserRegionsPixels(:,2), mserRegionsPixels(:,1));
mserMask(ind) = true;
% Run the edge detector
edgeMask = edge(grayImage, 'Canny');
% Find intersection between edges and MSER regions
edgeAndMSERIntersection = edgeMask & mserMask;
figure; imshowpair(edgeMask, edgeAndMSERIntersection, 'montage');
title('Canny edges and intersection of canny edges with MSER regions')

Note that the original MSER regions in mserMask still contain pixels that are not part of the text.
We can use the edge mask together with edge gradients to eliminate those regions.

Grow the edges outward by using image gradients around edge


locations. helperGrowEdges helper function.
[~, gDir] = imgradient(grayImage);
% You must specify if the text is light on dark background or vice versa
gradientGrownEdgesMask = helperGrowEdges(edgeAndMSERIntersection, gDir,
'LightTextOnDark');
figure; imshow(gradientGrownEdgesMask); title('Edges grown along gradient direction')

This mask can now be used to remove pixels that are within the MSER regions but are likely not
part of text.
% Remove gradient grown edge pixels
edgeEnhancedMSERMask = ~gradientGrownEdgesMask & mserMask;
% Visualize the effect of segmentation

figure; imshowpair(mserMask, edgeEnhancedMSERMask, 'montage');


title('Original MSER regions and segmented MSER regions')

In this image, letters have been further separated from the background and many of the non-text
regions have been separated from text.
Step 4: Filter Character Candidates Using Connected Component Analysis
Some of the remaining connected components can now be removed by using their region
properties. The thresholds used below may vary for different fonts, image sizes, or languages.
connComp = bwconncomp(edgeEnhancedMSERMask); % Find connected components
stats = regionprops(connComp,'Area','Eccentricity','Solidity');
% Eliminate regions that do not follow common text measurements
regionFilteredTextMask = edgeEnhancedMSERMask;
regionFilteredTextMask(vertcat(connComp.PixelIdxList{[stats.Eccentricity] > .995})) = 0;
regionFilteredTextMask(vertcat(connComp.PixelIdxList{[stats.Area] < 150 | [stats.Area] >
2000})) = 0;
regionFilteredTextMask(vertcat(connComp.PixelIdxList{[stats.Solidity] < .4})) = 0;
% Visualize results of filtering
figure; imshowpair(edgeEnhancedMSERMask, regionFilteredTextMask, 'montage');
title('Text candidates before and after region filtering')

Step 5: Filter Character Candidates Using the Stroke Width Image


Another useful discriminator for text in images is the variation in stroke width within each text
candidate. Characters in most languages have a similar stroke width or thickness throughout. It is
therefore useful to remove regions where the stroke width exhibits too much variation [1]. The
stroke width image below is computed using thehelperStrokeWidth helper function.
distanceImage = bwdist(~regionFilteredTextMask); % Compute distance transform
strokeWidthImage = helperStrokeWidth(distanceImage); % Compute stroke width image
% Show stroke width image
figure; imshow(strokeWidthImage);
caxis([0 max(max(strokeWidthImage))]); axis image, colormap('jet'), colorbar;
title('Visualization of text candidates stroke width')

Note that most non-text regions show a large variation in stroke width. These can now be filtered
using the coefficient of stroke width variation.
% Find remaining connected components
connComp = bwconncomp(regionFilteredTextMask);
afterStrokeWidthTextMask = regionFilteredTextMask;
for i = 1:connComp.NumObjects

strokewidths = strokeWidthImage(connComp.PixelIdxList{i});
% Compute normalized stroke width variation and compare to common value
if std(strokewidths)/mean(strokewidths) > 0.35
afterStrokeWidthTextMask(connComp.PixelIdxList{i}) = 0; % Remove from text
candidates
end
end
% Visualize the effect of stroke width filtering
figure; imshowpair(regionFilteredTextMask, afterStrokeWidthTextMask,'montage');
title('Text candidates before and after stroke width filtering')

Step 6: Determine Bounding Boxes Enclosing Text Regions


To compute a bounding box of the text region, we will first merge the individual characters into a
single connected component. This can be accomplished using morphological closing followed by
opening to clean up any outliers.
se1=strel('disk',25);
se2=strel('disk',7);
afterMorphologyMask = imclose(afterStrokeWidthTextMask,se1);
afterMorphologyMask = imopen(afterMorphologyMask,se2);
% Display image region corresponding to afterMorphologyMask
displayImage = colorImage;

displayImage(~repmat(afterMorphologyMask,1,1,3)) = 0;
figure; imshow(displayImage); title('Image region under mask created by joining individual
characters')

Find bounding boxes of large regions.


areaThreshold = 5000; % threshold in pixels

connComp = bwconncomp(afterMorphologyMask);
stats = regionprops(connComp,'BoundingBox','Area');
boxes = round(vertcat(stats(vertcat(stats.Area) > areaThreshold).BoundingBox));
for i=1:size(boxes,1)
figure;
imshow(imcrop(colorImage, boxes(i,:))); % Display segmented text
title('Text region')
end

Step 7: Perform Optical Character Recognition on Text Region

The segmentation of text from a cluttered scene can greatly improve OCR results. Since our
algorithm already produced a well segmented text region, we can use the binary text mask to
improve the accuracy of the recognition results.
ocrtxt = ocr(afterStrokeWidthTextMask, boxes); % use the binary image instead of the color
image
ocrtxt.Text
ans =
LE
HANDICAPPED
PARKING
SPECIAL PLATE
REQUIRED
UNAUTHORIZED
VEHICLES
MAY BE TOWED
AT OWNERS
EXPFNSE

Step 8: Apply the Text Detection Process to Other Images


To highlight flexibility of this approach, we will apply the entire algorithm to other images using
thehelperDetectText helper function.
Process image containing three posters.
languageImage = imread('posters.jpg');
boxes = helperDetectText(languageImage);
% Visualize the results
figure; imshow(languageImage); title('Posters with different languages')
hold on
for i=1:size(boxes,1)
rectangle('Position', boxes(i,:),'EdgeColor','r')
end

Below, we will process an image containing three license plates. License plates usually have
white or gray background with a darker text color. This requires that the edges are grown in the
opposite direction. Additionally, the maximum eccentricity threshold must be adjusted since
license plate characters are relatively thin. Both of these parameters can be supplied to the helper
function.
plateImage = imread('licensePlates.jpg');
eccentricityThreshold = 0.995;

boxes = helperDetectText(plateImage,'TextPolarity','DarkTextOnLight',...
'MaxEccentricity', eccentricityThreshold, 'SizeRange', [200,2000]);
figure; imshow(plateImage); title('License plates'); hold on
for i=1:size(boxes,1)
rectangle('Position', boxes(i,:),'EdgeColor','r')
end

References
[1] Chen, Huizhong, et al. "Robust Text Detection in Natural Images with Edge-Enhanced
Maximally Stable Extremal Regions." Image Processing (ICIP), 2011 18th IEEE International
Conference on. IEEE, 2011.

Translated
Secara otomatis mendeteksi dan mengenali teks dalam gambar alam
Membuka contoh ini
Contoh ini menunjukkan bagaimana mendeteksi daerah yang mengandung teks dalam
gambar. Ini adalah tugas yang biasa dilakukan pada adegan-adegan yang terstruktur,
misalnya ketika menangkap video dari kendaraan pindah untuk tujuan memperingatkan
seorang sopir tentang tanda jalan. Segmentasi teks dari adegan berantakan sangat
membantu dengan tugas-tugas tambahan seperti pengenalan karakter optik (OCR).
Algoritma deteksi otomatis teks dalam contoh ini dimulai dengan sejumlah besar teks
wilayah kandidat dan semakin menghilangkan mereka cenderung berisi teks. Untuk
menyoroti fleksibilitas algoritma ini, hal ini diterapkan untuk gambar yang berisi tanda
jalan, poster dan serangkaian pelat lisensi.
Langkah 1: Load image
Memuat gambar. Teks dapat diputar di pesawat, tapi signifikan dari rotasi pesawat
mungkin memerlukan pra-proses tambahan.
Code 1
gambar

Langkah 2: Mendeteksi MSER daerah


Karena karakter teks biasanya memiliki warna yang konsisten, kita mulai dengan
mencari daerah intensitas yang sama pada gambar dengan menggunakan MSER
wilayah detektor [1].
gambar
Beberapa daerah ini termasuk latar belakang tambahan piksel. Pada tahap ini, huruf
E dan D di "TOWED" menggabungkan menjadi satu wilayah. Perhatikan juga bahwa
ruang di antara batu bata disertakan.
Langkah 3: Gunakan Canny Edge detektor untuk lebih lanjut segmen teks
Karena teks tertulis biasanya diletakkan di jelas latar belakang, ia cenderung untuk
menghasilkan respon tinggi untuk deteksi tepi. Selain itu, persimpangan MSER
daerah dengan tepi akan menghasilkan daerah yang lebih cenderung milik teks.
gambar
Dicatat bahwa daerah MSER asli di mserMask masih mengandung pixel yang bukan
merupakan bagian dari teks. Kita dapat menggunakan masker tepi bersama-sama
dengan gradien tepi untuk menghilangkan daerah tersebut.
gambar

Tumbuh tepi luar dengan menggunakan gambar gradien sekitar lokasi tepi. fungsi
helperGrowEdges.
gambar
Mask ini sekarang dapat digunakan untuk menghapus pixel yang berada dalam
daerah MSER tetapi mungkin tidak bagian teks.
gambar
Dalam gambar ini, tulisan telah lebih lanjut dipisahkan dari latar belakang dan
banyak dari wilayah non-teks telah dipisahkan dari teks.
Langkah 4: Filter karakter kandidat menggunakan analisis komponen terhubung
Beberapa komponen terhubung yang tersisa dapat dilepaskan dengan
menggunakan properti wilayah mereka. Ambang batas yang digunakan di bawah ini
mungkin berbeda untuk font yang berbeda, ukuran gambar atau bahasa.
Gambar
Langkah 5: Filter karakter kandidat menggunakan Stroke lebar gambar
Lain berguna diskriminator untuk teks dalam gambar adalah variasi stroke lebar
dalam setiap calon teks. Karakter dalam kebanyakan bahasa memiliki serupa lebar
stroke atau ketebalan seluruh. Hal ini karena itu berguna untuk menghapus daerah
mana lebar stroke pameran terlalu banyak variasi [1]. Stroke lebar gambar di
bawah ini dihitung dengan menggunakan fungsi helperStrokeWidth.
Gambar
Dicatat bahwa daerah non-teks yang paling menunjukkan variasi besar lebar stroke.
Ini dapat sekarang disaring menggunakan koefisien stroke lebar variasi.
gambar
Langkah 6: Menentukan berlari kotak melampirkan teks daerah
Untuk menghitung kotak yang melompat-lompat dari wilayah teks, kita pertama
akan menggabungkan karakter individu menjadi satu komponen terhubung. Ini
dapat dicapai dengan menggunakan penutupan morfologi yang diikuti dengan
pembukaan untuk membersihkan outliers apapun.
Gambar
Menemukan kotak melompat-lompat daerah besar.
Gambar

Langkah 7: Melakukan pengenalan karakter optik di wilayah teks

Segmentasi teks dari adegan berantakan dapat sangat meningkatkan hasil OCR.
Karena algoritma kami sudah menghasilkan sebuah teks baik tersegmentasi
daerah, kita dapat menggunakan masker biner teks untuk meningkatkan akurasi
hasil pengakuan.
Gambar
ans =
LE
HANDICAPPED
PARKING
SPECIAL PLATE
REQUIRED
UNAUTHORIZED
VEHICLES
MAY BE TOWED
AT OWNERS
EXPFNSE

Langkah 8: Menerapkan proses deteksi teks gambar lainnya


Untuk menyoroti fleksibilitas dari pendekatan ini, kami akan menerapkan algoritma
seluruh gambar lain menggunakan fungsi pembantu helperDetectText.
Proses gambar yang mengandung tiga poster.
Gambar
Di bawah ini, kami akan memproses sebuah citra berisi tiga piring lisensi. Plat
biasanya memiliki latar belakang putih atau abu-abu dengan warna teks gelap. Hal
ini memerlukan bahwa tepi tumbuh dalam arah yang berlawanan. Selain itu,
ambang batas maksimum eksentrisitas harus disesuaikan karena karakter plat
relatif tipis. Kedua parameter ini dapat diberikan untuk fungsi pembantu.
Gambar

Addition

Input Foto Menggunakan Webcam Dengan MATLAB


Di sini saya akan mencoba membantu teman-teman yang sedang mengalami
kesulitan dalam mencari source code real-time pada MATLAB. Dalam kasus ini, saya
menggunakan media webcam untuk mengambil foto objek data.
Pertama-tama cek terlebih dahulu apakah data acquisition toolbox pada MATLAB
sudah terinstalisasi atau belum. Untuk mengakses webcam dilakukan langkahlangkah sebagai berikut :
1.

Cek data acquisition, dengan klik menu Start pada MATLAB

2. Kemudian ketik imaqhinfo pada command window. Untuk lebih jelasnya


lihat gambar berikut ini

Untuk mendapatkan info tentang peralatannya, ketik:

info=imaqhwinfo['winvideo']

Perhatikan bahwa adaptor adalah winvideo. Setiap webcam yang terhubung


diakses melalui adaptor ini.

Inisialisasi perangkat keras (adaptor) sebagai objek. Instruksi yang digunakan


dalam MATLAB adalah:
obj = videoinput(adaptorname,deviceID,format)

Untuk mengetahui parameter deviceID, dan format, ketikkan perintah berikut


dalam MATLAB:
get(vd)

Memberikan
nilai
pada
parameter
perangkat
keras.
Dengan
perintah get(vd), dapat diketahui parameter apa saja yang ada pada webcam.
Lalu dari parameter tersebut, beberapa diantaranya bisa diset. Untuk mengetahui
parameter apa saja yang bisa diset, gunakan perintah berikut ini:
set(vd)
Buka preview window untuk melihat video pada saatruntime. Berikut adalah
sintaksnya:
preview(vid);

Perintah ini akan membuka jendela yang sama dengan interface padayahoo
messanger webcam. Dan bisa melihat demo video webcam pada saat runtime.
Pengambilan gambar. Berikut adalah sintaksnya:

data = getsnapshot(vid);

Ini

berarti

variabel data menyimpan

data

citra

digital

yang

telah

diambil

menggunakan webcam. Perintah ini akan menyimpan gambar dengan cepat ke


dalam variabel data dalam sebuah matriks berukuran 320240. Lalu, untuk

menampilkan hasil snapshot tidak bisa menggunakan perintah imshow. Karena


data ini masih berupa data matriks, perlu menggunakan perintah lain untuk
mengubah

matriks

tersebut

ke

citra

lalu

menampilkannya

sebagai

citra.

image(gambar);

atau
start(vid);

im=getdata(vid,1);

figure,imshow(im);

Di sini, variable vid harus didefinisikan terlebih dahulu, kemudian gunakan perintah
getdata

untuk

mengambil

gambar.

Penyimpanan gambar. Gambar bisa disimpan dalam bentuk .jpg atau .gif.
Untuk menyimpan gambar dapat digunakan perintah imwrite.
imwrite(im,myfirstimage.jpg);

Berikut

ini

adalah

contoh

source

code

yang

saya

gunakan:

% --- Executes on button press in Btn_gambar.


function Btn_gambar_Callback(hObject, eventdata, handles)
% hObject

handle to pushbutton1 (see GCBO)

% eventdata

reserved - to be defined in a future version of MATLAB

% handles

structure with handles and user data (see GUIDATA)

imaqhwinfo;
foto=videoinput('winvideo');
%foto=videoinput('winvideo',1,'RGB24_13484480x2084362783');
set(foto,'SelectedSourceName','input1');
foto.ReturnedColorSpace='rgb';
foto.FramesPerTrigger=100;
%imaqmem('FrameMemoryLimit');
%axes(handles.axes1);
start(foto);
gambar=getsnapshot(foto);
imaqmontage(gambar);
image(gambar);
%axis xy;
%axis

'autoy';

Keterangan: jika ingin mengatur nilai x dan y, hapus tanda '%'.

Semoga tulisan saya ini bermanfaat :) Selamat Mencoba!!!

Dalam kesempatan ini saya ingin mencoba berbagi cerita tentang pengolahan video
(video processing). Salah satu proses yang seringkali kita butuhkan dalam pengolahan
video adalah mengubah video tersebut menjadi gambar. Sebelumnya mari kita ulas
terlebih dahulu mengenai video. Seperti yang kita tahu video ini terdiri dari beberapa
gambar yang terurut (image sequences) disebut dengan frame. Dengan demikian kita
dapat menghasilkan gambar dari suatu file video, ataupun sebaliknya kita dapat
menghasilkan file video dari beberapa gambar yang terurut tersebut.
Mari kita langsung lihat bagaimana cara mengambil gambar gambar/frame tersebut
dari video menggunakan matlab. Saya menggunakan matlab 2013a, mari langsung
saja kita liat tahapan tahapannya :
Setup lokasi penyimpanan

Pada tahap ini akan dibuat sebuah folder yang akan digunkan sebagi tempat
penyimpanan dari hasil konversi video ke gambar tersebut.

pathDir = 'D:\Matlab\Coba\Video2ImageConvert';
workingDir = 'fileImg';
% Memebuat folder
mkdir(pathDir,workingDir);
Keterangan :
PathDir merupakan path atau lokasi dari folder yang akan dibuat.
WorkingDir merupakan nama dari folder yang akan dibuat.
Ketika ingin membuat folder pada lokasi dimana source code matlab ini terletak maka
tidak perlu menambahkan lokasi (pathDir). Sehingga pada code untuk pembuatan
folder menjadi mkdir(namaFolder).
Setup video
Pada tahap ini program akan membaca video kemudian memeriksa jumlah dari frame
dalam video tersebut.

video = mmreader('pedestrian.FLV');
file=read(video);
frm_cnt=video.NumberOfFrames
Keterangan :

Mmreader merupakan salah satu class dari matlab yang digunakan untuk
membaca file video.

Read merupakan salah satu fungsi dari class videoreader pada matlab yang
digunakan untuk membaca object. Dalam penerapan kali ini read berfungsi
untuk membaca semua frame dari video.

Untuk mendapatkan jumlah frame dari video tersebut maka sebagaimana telah tertulis
pada kode diatas menggunakan : NamaObj.NumberOfFrames.

Setup waitbar
Tahap ini digunakan kerika ingin menambahkan window loading pada saat menunggu
proses konversi. Ini dapat berfungsi sebagai indikator proses berjalan sebagaimana
mestinya atau tidak. Dalam pembuatan waitbar ini terdapat 2 proses yaitu inisialisasi
waitbar dan update waitbar. Pada prinsipnya waitbar ini akan display dari waitbar ini
akan diupdate sesuai dengan persentasi proses yang dilakukan dalam program
tersebut.

% inisialisasi waitbar
load = waitbar(0,'Please wait');
% update waitbar
waitbar(i/frm_cnt,load)

Konversi Video ke Gambar


Dalam tahap ini video tersebut akan dibaca per frame dan diinput pada sebuah
variable kemudian dibuat image dari variable tersebut.

%looping all frame


for i=1:frm_cnt

% read video per frame


frm=read(video,i);
% set label image
filename=[sprintf('image%03d',i) '.jpg'];
fullname= fullfile(workingDir,filename);
% create image from reading frame
imwrite(frm,fullname);
% update waitbar
waitbar(i/frm_cnt,load)
end
Program ini diulang sebanyak jumlah frame yang ada pada video tersebut, kemudian
dilakukan pembacaan video tiap framenya. Selanjutnya menyediakan label atau nama
dari image dengan :
filename=[sprintf('image%03d',i) '.jpg'];
fullname= fullfile(workingDir,filename);
dimana sprintf ini digunakan untuk menggabungkan antara string dan variable
sedangkan fullfile digunakan untuk menentukan letak dari file image tersebut.
Terakhir barulah membuat image dari tiap tiap frame yang dibaca dengan sesuai
format yang ditentukan:
imwrite(frm,fullname).
Apabila program matlab tersebut dijalankan, maka akan terbentuk gambar setiap
frame dari video. Sebagai berikut:

You might also like