GithubHelp home page GithubHelp logo

picg's People

Watchers

James Cloos avatar Ian Silva avatar

picg's Issues

Marcação de Objetos na Imagem

%matplotlib inline
import numpy as np
import cv2
import imutils
import matplotlib.pyplot as plt

Carrega a imagem

image = cv2.imread("image_teste.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Exibe a imagem original

plt.imshow(image)
plt.show()

Busca todas a bordas de objetos e desenha contordos sobre elas

cnts = cv2.findContours(gray.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
clone = image.copy()
cv2.drawContours(clone, cnts, -1, (0, 255, 0), 2)
print("{} Contornos encontrados".format(len(cnts)))

Exibe a imagem

plt.imshow(clone)
plt.show()

for (i, c) in enumerate(cnts):
# calcular a área e o perímetro do contorno
area = cv2.contourArea(c)
perimeter = cv2.arcLength(c, True)
print("Contorno #{} -- area: {:.2f}, perimetro: {:.2f}".format(i + 1, area, perimeter))

# desenhe o contorno na imagem
cv2.drawContours(clone, [c], -1, (0, 255, 0), 2)

# calcular o centro do contorno e desenhar o número do contorno
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
cv2.putText(clone, "#{}".format(i + 1), (cX - 20, cY), cv2.FONT_HERSHEY_SIMPLEX,
	1.25, (255, 255, 255), 4)

Exibe imagem

plt.imshow(clone)
plt.show()

clone = image.copy()

loop sobre os contornos

for c in cnts:
# encaixar uma caixa delimitadora no contorno
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(clone, (x, y), (x + w, y + h), (0, 255, 0), 2)

mostra a imagem de saída

plt.imshow(clone)
plt.show()
clone = image.copy()

Processamento de Texto

import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import resize, rotate
from skimage.color import rgb2gray, rgb2gray
from skimage.filters import threshold_otsu
from skimage import exposure

Leitura da imagem

img = plt.imread('./IMAG0027.JPG')
plt.title('Imagem Original')
plt.imshow(img)
plt.axis('off')
plt.show()

#Tons de cinza
img_gray = rgb2gray(img)
plt.title('Imagem em tons de cinza')
plt.imshow(img_gray)
plt.axis('off')
plt.show()

EXIBINDO A IMAGEM EM PRETO E BRANCO

Binarização (threshold otsu)

thresh = threshold_otsu(img_gray)
binary_thresh_img = img_gray > thresh
plt.title('Aplicando threshold otsu')
plt.imshow(binary_thresh_img)
plt.axis('off')
plt.show()
print(binary_thresh_img.shape)

Binarização Inverter preto e branco (threshold otsu invertida)

thresh = threshold_otsu(img_gray)
binary_thresh_img = img_gray < thresh
plt.title('Aplicando threshold otsu invertida')
plt.imshow(binary_thresh_img)
plt.axis('off')
plt.show()
print(binary_thresh_img.shape)

Dilatando imagem

from skimage import morphology
dilatacao = morphology.dilation(binary_thresh_img)
plt.title('Dilatando imagem Otsu invertida')
plt.imshow(dilatacao)
plt.axis('off')
plt.show()

Imagens equalizadas

im_eq = exposure.equalize_hist(dilatacao)
im_adapthist = exposure.equalize_adapthist(img_gray, clip_limit=0.05)
plt.title('Dilatando imagem Otsu invertida equalizada')
plt.imshow(im_eq)
plt.axis('off')
plt.show()
plt.imshow(im_adapthist)
plt.axis('off')
plt.show()

Operações (Rotação, Redimensionamento, Media, Mediana, Variancia, Conversao RGB HSV Gray, Historigrama)

Redimensionamento e rotação

import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import resize, rotate

Leitura da imagem

img = plt.imread('./image01.jpg')
l,a,c = img.shape

Redimencionamento

img_red = resize(img, (l / 2, a / 2))

Rotacionar imagem

img_rot = rotate(img, 90, resize=True)

plt.imshow(img)
plt.show()
plt.imshow(img_red)
plt.show()
plt.imshow(img_rot)
plt.show()
plt.imsave('img_red.jpg', img_red)

Detectando Contornos

Detectando Contornos na imagem

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

Leitura da imagem e print de algumas estatísticas

image = mpimg.imread('moedas.jpg')
print('Esta imagem é um objeto: ',type(image), 'com as seguintes dimensões:', image.shape)
plt.imshow(image)
plt.show()

Obtém o tamanho de x e y e faz uma cópia da imagem

xsize = image.shape[0]
ysize = image.shape[1]
print('Linhas: ', xsize)
print('Colunas: ', ysize)

Dica: sempre faça uma cópia da imagem antes de qualquer alteração na imagem original

color_select = np.copy(image)

Define os critérios de seleção de cores (o valor 230 foi escolhido aleatoriamente)

red_threshold = 230
green_threshold = 230
blue_threshold = 230

Limites das cores RGB

rgb_threshold = [red_threshold, green_threshold, blue_threshold]

Identifica os pixels abaixo do limite (threshold)

Depois disso, todos os pixels que atendam ao nosso critério de cores (aqueles acima do limite) serão mantidos

e aqueles que não atendem (abaixo do limite) serão apagados.

thresholds = (image[:,:,0] < rgb_threshold[0])
| (image[:,:,1] < rgb_threshold[1])
| (image[:,:,2] < rgb_threshold[2])

O resultado, color_select, é uma imagem na qual os pixels que estavam acima do limite foram retidos

e os pixels abaixo do limite foram apagados.

color_select[thresholds] = [0,0,0]

Print da imagem

plt.imshow(color_select)
plt.show()

Mofologia

import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

Carregando a imagem e transformando em tons de cinza

image = cv2.imread("carro.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Construir um kernel e aplicar morfologia

rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 5))
blackhat = cv2.morphologyEx(gray, cv2.MORPH_BLACKHAT, rectKernel)

tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel)

plt.imshow(image)
plt.show()
plt.imshow(blackhat)
plt.show()
plt.imshow(tophat)
plt.show()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.