Nugroho's blog.: Vertical Sobel Operator Manual Edge Detection using Python and PIL

## Saturday, December 17, 2011

### Vertical Sobel Operator Manual Edge Detection using Python and PIL

This python code is used to detect the edge, of course, using Sobel Operator. The 'manual' word in this post title means I apply it manually as scipy python module has it capability. This code convert a jpeg image to grayscale and then detect its edge.

Here the code, I used vertical detection only as my horizontal code result is scrambling. I will update it as soon as all code success

`print 'Program Python Deteksi Tepi'print 'oleh Nugroho Adi Pramono''''Komentar diantara tiga-tanda petik tidak akan dibacaoleh python'''#komentar setelah tanda pagar juga tidak di baca oleh pythonimport Image        #memanggil modul untuk olah gambarimport os,sys       #memanggil modul untuk mengakses fileimport numpy as np  #memanggil modul untuk operasi maatematika matrik/arraygb = Image.open('../gambar.jpg')                   #memasukkan gambar ke variabel gbprint 'format awal: ' ,gb.format, "%dx%d" % gb.size, gb.modeprint 'konversi ke grayscale'gbw = gb.convert("L")gbw.save('gambarBW.jpg')                #simpan hasil konversi ddg nama gambarBW.jpggbw = Image.open('gambarBW.jpg')        #masukkan gambar grayscale hasil konversi ke variabel gbwprint 'format: ',gbw.format, "%dx%d" % gbw.size, gbw.modeukuran=gbw.size                         #mengambil nilai resolusi gambar'''buat array r dan s berukuran sama dengan ukuran gambar'''r=np.zeros((ukuran[0],ukuran[1]),dtype=np.integer)s=np.zeros((ukuran[0],ukuran[1]),dtype=np.integer)print 'Mengambil nilai piksel, masukkan ke array r'for i in range (ukuran[0]):    for j in range (ukuran[1]):        r[i,j]=gbw.getpixel((i,j))print 'Deteksi tepi menggunakan operator Sobel'gx=np.zeros((ukuran[0],ukuran[1]),dtype=np.integer)gy=np.zeros((ukuran[0],ukuran[1]),dtype=np.integer)g=np.zeros((ukuran[0],ukuran[1]),dtype=np.float)for i in range (1,ukuran[0]-1):    for j in range (1,ukuran[1]-1):        gy[i,j]=r[i+1,j-1]+2*r[i+1,j]+r[i+1,j+1]-r[i-1,j-1]-2*r[i-1,j]-r[i-1,j+1]print 'Atur threshold'print 'update gambar Vertikal'for i in range (ukuran[0]):    for j in range (ukuran[1]):        gbw.putpixel((i,j),np.abs(gy[i,j]))      #letakkan pixel yang telah dimodifikasi ke posisi i,jprint 'Menyimpan gambar Vertikal'gbw.save('gambarSobelVertikal.jpg')          #simpan dengan nama gambarSobelVertikal.jpgprint 'Gambar tersimpan'print 'Program Selesai'`
And here the result

Image source
 From python

Gray-scaled image
 From python

Edge-detected image
 From python