Lab06 - Transformada de Hough e morfologia
Objetivos da aula:
- Conhecer e praticar a Transformada de Hough para linhas e circulos
- conhecer e praticar com os operadores de dilatação e erosão
- conhecer e praticar com os operadores de abertura e fechamento
Transformada de Hough¶
A transformada de Hough é um metodo utilizado para reconhecimento de padrões simples como retas e circulos. a aplicação da técnica é feita em contornos de imagem. É uma técnica muito popular e muito poderosa, pois possibilita detectar linhas e circulos em imagens com pouco visível ou muito ruidosa.
####----- FAZENDO O DOWNLOAD DAS IMAGENS DO RESPOSITÓRIO, APENAS PARA FACILITAR -----#####
## SE ESTIVER RODANDO EM SUA MÁQUINA LOCAL NÃO PRECISA RODAR ESSA CELULA ##
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/coins.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/corredor.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/dilatação.gif /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/erosao.gif /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/formas.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/formas_contorno.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/formas_contornor.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/j-noise.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/j.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/holes.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/melancia_filtrada.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/melancia_filtrada_rgb.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/moeda1.jpg /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/pessoas-gif.gif /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/rua.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/sala.jpg /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/sala1.jpg /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/sala2.jpg /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/sala3.jpg /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/sala_res.png /content
!wget https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/PDI/lab06/people-walking.mp4 /content
--2023-03-09 12:22:12-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/coins.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 819309 (800K) [image/png] Saving to: ‘coins.png.2’ coins.png.2 0%[ ] 0 --.-KB/s coins.png.2 100%[===================>] 800.11K --.-KB/s in 0.02s 2023-03-09 12:22:12 (42.9 MB/s) - ‘coins.png.2’ saved [819309/819309] /content: Scheme missing. FINISHED --2023-03-09 12:22:12-- Total wall clock time: 0.05s Downloaded: 1 files, 800K in 0.02s (42.9 MB/s) --2023-03-09 12:22:13-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/corredor.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 1108883 (1.1M) [image/png] Saving to: ‘corredor.png.1’ corredor.png.1 100%[===================>] 1.06M --.-KB/s in 0.02s 2023-03-09 12:22:13 (54.9 MB/s) - ‘corredor.png.1’ saved [1108883/1108883] /content: Scheme missing. FINISHED --2023-03-09 12:22:13-- Total wall clock time: 0.04s Downloaded: 1 files, 1.1M in 0.02s (54.9 MB/s) --2023-03-09 12:22:13-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/dilata%C3%A7%C3%A3o.gif Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 90056 (88K) [image/gif] Saving to: ‘dilatação.gif.1’ dilatação.gif.1 100%[===================>] 87.95K --.-KB/s in 0.005s 2023-03-09 12:22:13 (16.3 MB/s) - ‘dilatação.gif.1’ saved [90056/90056] /content: Scheme missing. FINISHED --2023-03-09 12:22:13-- Total wall clock time: 0.04s Downloaded: 1 files, 88K in 0.005s (16.3 MB/s) --2023-03-09 12:22:13-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/erosao.gif Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 77526 (76K) [image/gif] Saving to: ‘erosao.gif.1’ erosao.gif.1 100%[===================>] 75.71K --.-KB/s in 0.005s 2023-03-09 12:22:13 (15.2 MB/s) - ‘erosao.gif.1’ saved [77526/77526] /content: Scheme missing. FINISHED --2023-03-09 12:22:13-- Total wall clock time: 0.03s Downloaded: 1 files, 76K in 0.005s (15.2 MB/s) --2023-03-09 12:22:13-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/formas.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 34765 (34K) [image/png] Saving to: ‘formas.png.1’ formas.png.1 100%[===================>] 33.95K --.-KB/s in 0.001s 2023-03-09 12:22:13 (40.6 MB/s) - ‘formas.png.1’ saved [34765/34765] /content: Scheme missing. FINISHED --2023-03-09 12:22:13-- Total wall clock time: 0.02s Downloaded: 1 files, 34K in 0.001s (40.6 MB/s) --2023-03-09 12:22:13-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/formas_contorno.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 22192 (22K) [image/png] Saving to: ‘formas_contorno.png.1’ formas_contorno.png 100%[===================>] 21.67K --.-KB/s in 0.001s 2023-03-09 12:22:13 (30.5 MB/s) - ‘formas_contorno.png.1’ saved [22192/22192] /content: Scheme missing. FINISHED --2023-03-09 12:22:13-- Total wall clock time: 0.03s Downloaded: 1 files, 22K in 0.001s (30.5 MB/s) --2023-03-09 12:22:13-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/formas_contornor.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 22192 (22K) [image/png] Saving to: ‘formas_contornor.png.1’ formas_contornor.pn 100%[===================>] 21.67K --.-KB/s in 0.001s 2023-03-09 12:22:13 (34.5 MB/s) - ‘formas_contornor.png.1’ saved [22192/22192] /content: Scheme missing. FINISHED --2023-03-09 12:22:13-- Total wall clock time: 0.02s Downloaded: 1 files, 22K in 0.001s (34.5 MB/s) --2023-03-09 12:22:13-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/j-noise.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 9306 (9.1K) [image/png] Saving to: ‘j-noise.png.1’ j-noise.png.1 100%[===================>] 9.09K --.-KB/s in 0s 2023-03-09 12:22:13 (88.6 MB/s) - ‘j-noise.png.1’ saved [9306/9306] /content: Scheme missing. FINISHED --2023-03-09 12:22:13-- Total wall clock time: 0.03s Downloaded: 1 files, 9.1K in 0s (88.6 MB/s) --2023-03-09 12:22:13-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/j.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 1126 (1.1K) [image/png] Saving to: ‘j.png.1’ j.png.1 100%[===================>] 1.10K --.-KB/s in 0s 2023-03-09 12:22:13 (56.5 MB/s) - ‘j.png.1’ saved [1126/1126] /content: Scheme missing. FINISHED --2023-03-09 12:22:13-- Total wall clock time: 0.02s Downloaded: 1 files, 1.1K in 0s (56.5 MB/s) --2023-03-09 12:22:13-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/holes.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 11200 (11K) [image/png] Saving to: ‘holes.png’ holes.png 100%[===================>] 10.94K --.-KB/s in 0s 2023-03-09 12:22:14 (105 MB/s) - ‘holes.png’ saved [11200/11200] /content: Scheme missing. FINISHED --2023-03-09 12:22:14-- Total wall clock time: 0.2s Downloaded: 1 files, 11K in 0s (105 MB/s) --2023-03-09 12:22:14-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/melancia_filtrada.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 3956 (3.9K) [image/png] Saving to: ‘melancia_filtrada.png.1’ melancia_filtrada.p 100%[===================>] 3.86K --.-KB/s in 0s 2023-03-09 12:22:14 (66.0 MB/s) - ‘melancia_filtrada.png.1’ saved [3956/3956] /content: Scheme missing. FINISHED --2023-03-09 12:22:14-- Total wall clock time: 0.03s Downloaded: 1 files, 3.9K in 0s (66.0 MB/s) --2023-03-09 12:22:14-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/melancia_filtrada_rgb.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 76721 (75K) [image/png] Saving to: ‘melancia_filtrada_rgb.png.1’ melancia_filtrada_r 100%[===================>] 74.92K --.-KB/s in 0.004s 2023-03-09 12:22:14 (16.6 MB/s) - ‘melancia_filtrada_rgb.png.1’ saved [76721/76721] /content: Scheme missing. FINISHED --2023-03-09 12:22:14-- Total wall clock time: 0.03s Downloaded: 1 files, 75K in 0.004s (16.6 MB/s) --2023-03-09 12:22:14-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/moeda1.jpg Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 1519406 (1.4M) [image/jpeg] Saving to: ‘moeda1.jpg.1’ moeda1.jpg.1 100%[===================>] 1.45M --.-KB/s in 0.02s 2023-03-09 12:22:14 (71.5 MB/s) - ‘moeda1.jpg.1’ saved [1519406/1519406] /content: Scheme missing. FINISHED --2023-03-09 12:22:14-- Total wall clock time: 0.04s Downloaded: 1 files, 1.4M in 0.02s (71.5 MB/s) --2023-03-09 12:22:14-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/pessoas-gif.gif Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 19057644 (18M) [application/octet-stream] Saving to: ‘pessoas-gif.gif.1’ pessoas-gif.gif.1 100%[===================>] 18.17M --.-KB/s in 0.06s 2023-03-09 12:22:14 (300 MB/s) - ‘pessoas-gif.gif.1’ saved [19057644/19057644] /content: Scheme missing. FINISHED --2023-03-09 12:22:14-- Total wall clock time: 0.08s Downloaded: 1 files, 18M in 0.06s (300 MB/s) --2023-03-09 12:22:14-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/rua.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 536123 (524K) [image/png] Saving to: ‘rua.png.1’ rua.png.1 100%[===================>] 523.56K --.-KB/s in 0.02s 2023-03-09 12:22:14 (31.7 MB/s) - ‘rua.png.1’ saved [536123/536123] /content: Scheme missing. FINISHED --2023-03-09 12:22:14-- Total wall clock time: 0.04s Downloaded: 1 files, 524K in 0.02s (31.7 MB/s) --2023-03-09 12:22:14-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/sala.jpg Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 55082 (54K) [image/jpeg] Saving to: ‘sala.jpg.1’ sala.jpg.1 100%[===================>] 53.79K --.-KB/s in 0.004s 2023-03-09 12:22:14 (13.4 MB/s) - ‘sala.jpg.1’ saved [55082/55082] /content: Scheme missing. FINISHED --2023-03-09 12:22:14-- Total wall clock time: 0.03s Downloaded: 1 files, 54K in 0.004s (13.4 MB/s) --2023-03-09 12:22:14-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/sala1.jpg Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 57123 (56K) [image/jpeg] Saving to: ‘sala1.jpg.1’ sala1.jpg.1 100%[===================>] 55.78K --.-KB/s in 0.004s 2023-03-09 12:22:15 (13.9 MB/s) - ‘sala1.jpg.1’ saved [57123/57123] /content: Scheme missing. FINISHED --2023-03-09 12:22:15-- Total wall clock time: 0.03s Downloaded: 1 files, 56K in 0.004s (13.9 MB/s) --2023-03-09 12:22:15-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/sala2.jpg Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 57355 (56K) [image/jpeg] Saving to: ‘sala2.jpg.1’ sala2.jpg.1 100%[===================>] 56.01K --.-KB/s in 0.004s 2023-03-09 12:22:15 (14.0 MB/s) - ‘sala2.jpg.1’ saved [57355/57355] /content: Scheme missing. FINISHED --2023-03-09 12:22:15-- Total wall clock time: 0.03s Downloaded: 1 files, 56K in 0.004s (14.0 MB/s) --2023-03-09 12:22:15-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/sala3.jpg Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 55705 (54K) [image/jpeg] Saving to: ‘sala3.jpg.1’ sala3.jpg.1 100%[===================>] 54.40K --.-KB/s in 0.004s 2023-03-09 12:22:15 (12.7 MB/s) - ‘sala3.jpg.1’ saved [55705/55705] /content: Scheme missing. FINISHED --2023-03-09 12:22:15-- Total wall clock time: 0.03s Downloaded: 1 files, 54K in 0.004s (12.7 MB/s) --2023-03-09 12:22:15-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/sala_res.png Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 43494 (42K) [image/png] Saving to: ‘sala_res.png.1’ sala_res.png.1 100%[===================>] 42.47K --.-KB/s in 0.004s 2023-03-09 12:22:15 (11.8 MB/s) - ‘sala_res.png.1’ saved [43494/43494] /content: Scheme missing. FINISHED --2023-03-09 12:22:15-- Total wall clock time: 0.05s Downloaded: 1 files, 42K in 0.004s (11.8 MB/s) --2023-03-09 12:22:15-- https://raw.githubusercontent.com/arnaldojr/cognitivecomputing/master/material/aulas/lab06/people-walking.mp4 Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 8649411 (8.2M) [application/octet-stream] Saving to: ‘people-walking.mp4.1’ people-walking.mp4. 100%[===================>] 8.25M --.-KB/s in 0.04s 2023-03-09 12:22:15 (198 MB/s) - ‘people-walking.mp4.1’ saved [8649411/8649411] /content: Scheme missing. FINISHED --2023-03-09 12:22:15-- Total wall clock time: 0.07s Downloaded: 1 files, 8.2M in 0.04s (198 MB/s)
%matplotlib inline
import cv2
from matplotlib import pyplot as plt
import numpy as np
img = cv2.imread('formas.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.figure(figsize = (10,10))
plt.imshow(img); plt.show()
DETECÇÃO DE CIRCULOS¶
Vamos fazer a deteção de circulos da imagem forma.
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(img_gray,50,150)
circles=cv2.HoughCircles(edges,cv2.HOUGH_GRADIENT,dp=160,minDist=100,param1=200,param2=100,minRadius=50,maxRadius=150)
bordas_rgb = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
output = bordas_rgb
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
# desenha o contorno do circulo
cv2.circle(output,(i[0],i[1]),i[2],(0,255,0),2)
# desenha no centro do circulo
cv2.circle(output,(i[0],i[1]),2,(0,0,255),3)
plt.figure(figsize = (10,10))
plt.imshow(output, cmap="Greys_r", vmin=0, vmax=255); plt.show()
O resultado não ficou bom, pois há muitos falsos positivos detectados, neste caso precisamos alterar os parametros da transformada de hough. Vamos ver o que é cada um deles.
circles=cv2.HoughCircles(image,method=cv2.HOUGH_GRADIENT,dp,minDist,param1,param2,minRadius,maxRadius)
- image: imagem de entrada na escala de ciza.
- method: Define o metódo de detecção de circulos.
- dp: relação entre o tamanho da imagem e o tamanho do acumulador. Um dp grande "pega" bordas mais tênues.
- minDist: Distância minima entre centros (x,y) dos circulos detectados
- param1: Valor do gradiente usado para lidar com a detecção de bordas
- param2: Limiar do Acumulador usado pelo metódo. Se muito baixo, retorna mais circulos (incluindo círculos falsos). Se mais alto, mais círculos serão potencialmente retornados.
- minRadius: Raio minimo (em pixels).
- maxRadius: Raio máximo (em pixels).
DESAFIO 1¶
Faça a alteração dos parametros para a transformada de Hough afim de detectar apenas os circulos da imagem.
Dica: Altere um parametro por vez e analise o resultado.
# Implemente sua solução aqui...
import cv2 as cv
import numpy as np
img = cv.imread('coins.png',0)
img = cv.medianBlur(img,5)
cimg = cv.cvtColor(img,cv.COLOR_GRAY2BGR)
circles = cv.HoughCircles(img,cv.HOUGH_GRADIENT,1,20,param1=50,param2=40,minRadius=45,maxRadius=60)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
cv.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
plt.figure(figsize = (10,10))
plt.imshow(cimg)
<matplotlib.image.AxesImage at 0x7f6c31b2ea60>
DESAFIO 2¶
Modifique este código para detectar, segmentar e exibir a quantidade de moedas de 1 dólar. Neste imagem, temos quatro moedas de 1 dólar.
#Implemente seu código
DETECÇÃO DE RETAS¶
De forma semelhante ao CV2.HOUGHCIRCLE(), para detecção de retas usamos o cv2.HoughLines() ou cv2.HoughLinesP() o segundo faz uma estimativa probabilistica.
cv.HoughLinesP( image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]])
- imagem: Imagem de entrada em escala de cinza.
- rho: Resolução da distância do acumulador em pixeis.
- teta: Resolução do ângulo de rotação do acumulador em radianos, normalmente 1 Grau.
- threshold: Limiar do acumulador. Só são devolvidas as linhas que obtêm votos suficientes ( >threshold ).
- minLineLineLength: Comprimento mínimo da linha. Segmentos de linha mais curtos do que isso são rejeitados.
- maxLineGap: Distância máxima permitida entre pontos considerados na mesma linha.
%matplotlib inline
import cv2
from matplotlib import pyplot as plt
import numpy as np
import math
img = cv2.imread('formas.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.figure(figsize = (10,10))
plt.imshow(img); plt.show()
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(img_gray,50,150)
lines = cv2.HoughLinesP(edges, 1, math.pi/180.0, 100, np.array([]), 180, 5)
hough_img_rgb = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(hough_img_rgb, (x1, y1), (x2, y2), (255, 0, 255), 5)
plt.figure(figsize = (10,10))
plt.imshow(hough_img_rgb); plt.show()
DESAFIO 3¶
Faça a alteração dos parametros para a transformada de Hough afim de detectar apenas todas as linhas da imagem.
Dica: Altere um parametro por vez e analise o resultado.
#Implemente seu código
Exemplo mais prático, detecção de faixa por veiculos autonômos.
%matplotlib inline
import cv2
from matplotlib import pyplot as plt
import numpy as np
import math
img = cv2.imread('rua.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.figure(figsize = (10,10))
plt.imshow(img); plt.show()
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(img_gray,50,200)
lines = cv2.HoughLinesP(edges, 1, math.pi/180.0, 120, np.array([]), 10, 100)
hough_img_rgb = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(hough_img_rgb, (x1, y1), (x2, y2), (255, 0, 255), 5)
plt.figure(figsize = (10,10))
plt.imshow(hough_img_rgb); plt.show()
MORFOLOGIA MATEMÁTICA¶
A Morfologia Matemática (MM) é um modelo teórico para as imagens digitais construídas em cima da teoria dos reticulados e da topologia . É o fundamento do processamento de imagem morfológico, que é baseado nos operadores de deslocamento-invariante (translação invariante) baseados principalmente na adição de Minkowski.
DILATAÇÃO BINÁRIA¶
É uma transformação morfológica que combina dois conjuntos usando adição vetorial. Como o nome diz, o resultado será uma imagem “engordada”.
from IPython.display import Image
Image(open('dilatação.gif','rb').read())
import cv2 as cv
import numpy as np
img = cv.imread('j.png',0)
plt.imshow(img, cmap="Greys_r", vmin=0, vmax=255); plt.show()
kernel = np.ones((5,5),np.uint8)
dilation = cv.dilate(img,kernel,iterations = 1)
plt.imshow(dilation, cmap="Greys_r", vmin=0, vmax=255); plt.show()
Detectando contorno com dilatação¶
import cv2 as cv
import numpy as np
img = cv.imread('j.png',0)
plt.imshow(img, cmap="Greys_r", vmin=0, vmax=255); plt.show()
dst = img.copy()
kernel = np.ones((5,5),np.uint8)
dilation = cv.dilate(img,kernel,iterations = 1)
dst = dilation - img
plt.imshow(dst, cmap="Greys_r", vmin=0, vmax=255); plt.show()
EROSÃO BINÁRIA¶
A erosão basicamente encolhe uma imagem e pode ser vista como uma transformação morfológica que combina dois conjuntos usando vetores de subtração. Ela é expressa como a interseção de A e B.
from IPython.display import Image
Image(open('erosao.gif','rb').read())
import cv2 as cv
import numpy as np
img = cv.imread('j.png',0)
plt.imshow(img, cmap="Greys_r", vmin=0, vmax=255); plt.show()
dst = img.copy()
kernel = np.ones((5,5),np.uint8)
erode = cv.erode(img,kernel,iterations = 1)
plt.imshow(erode, cmap="Greys_r", vmin=0, vmax=255); plt.show()
DESAFIO 4¶
Utilizando a operação de erosão, calcule o contorno da imagem "j.png":
#implemente seu código...
ABERTURA BINÁRIA¶
A abertura em geral suaviza o contorno de uma imagem, quebra estreitos e elimina proeminências delgadas, a operação de abertura e usada também para remover ruídos da imagem.
import cv2 as cv
import numpy as np
img = cv.imread('j-noise.png',0)
plt.imshow(img, cmap="Greys_r", vmin=0, vmax=255); plt.show()
dst = img.copy()
kernel = np.ones((5,5),np.uint8)
opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
plt.imshow(opening, cmap="Greys_r", vmin=0, vmax=255); plt.show()
FECHAMENTO BINÁRIO¶
O fechamento funde pequenos quebras e alargas golfos estreitos elimina pequenos orifícios. Se uma abertura cria pequenos vazios na imagem, um fechamento irá preencher ou fechar os vazios, estas operações podem remover muitos dos pixels brancos com ruídos, ou seja basicamente ele e igual a abertura só que primeiramente e feita a dilatação e após e feita a erosão.
import cv2 as cv
import numpy as np
img = cv.imread('holes.png',0)
plt.imshow(img, cmap="Greys_r", vmin=0, vmax=255); plt.show()
dst = img.copy()
kernel = np.ones((5,5),np.uint8)
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
plt.imshow(closing, cmap="Greys_r", vmin=0, vmax=255); plt.show()
DESAFIO 5¶
Utilizando a operação abertura e depois a operação de fechamento binário, é esperado que a imagem volte ao original? Por que?
### seu código ###