Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import cv2
- from matplotlib import pyplot as plt
- img = cv2.imread('der.jpg')
- plt.imshow(img)
- plt.show()
- mask = np.zeros(img.shape[:2],np.uint8)
- bgdModel = np.zeros((1,65),np.float64)
- fgdModel = np.zeros((1,65),np.float64)
- rect = (500,400,1000,1250)
- cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
- mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
- img = img*mask2[:,:,np.newaxis]
- plt.imshow(img),plt.colorbar(),plt.show()
- img2 = cv2.imread('der2.jpg',0)
- # whereever it is marked white (sure foreground), change mask=1
- # whereever it is marked black (sure background), change mask=0
- print(mask.shape)
- print(img2.shape)
- mask[img2 == 0] = 0
- mask, bgdModel, fgdModel = cv2.grabCut(img,mask,None,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK)
- mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
- img = img*mask[:,:,np.newaxis]
- indices = np.column_stack(np.where(img != 0))
- print(indices)
- #top = max(indices[:,1])
- #bot = min(indices[:,1])
- #left = max(indices[:,0])
- #right = min(indices[:,0])
- imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
- ret, thresh = cv2.threshold(imgray,20,255,3)
- contours, hierarchy = cv2.findContours(thresh, 1, 2)
- cnt = contours[0]
- x,y,w,h = cv2.boundingRect(cnt)
- print(x)
- print(y)
- print(w)
- print(h)
- cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
- plt.imshow(img),plt.colorbar(),plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement