-
Notifications
You must be signed in to change notification settings - Fork 1
/
back.py
54 lines (40 loc) · 1.33 KB
/
back.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import cv2
from random import randint
import numpy as np
from matplotlib import pyplot as plt
#
# img=cv2.imread('try.jpg')
# mask=np.zeros(img.shape[:2],np.uint8)
#
# bgdModel=np.zeros((1,65),np.float64)
# fgdModel=np.zeros((1,65),np.float64)
#
# rect=(100,50,421,378)
# 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.subplot(121),plt.imshow(img)
# plt.title("grabcut"),plt.xticks([]),plt.yticks([])
# plt.subplot(122),
# plt.imshow(cv2.cvtColor(cv2.imread('try.jpg'),cv2.COLOR_BGR2RGB))
# plt.title("original"),plt.xticks([]),plt.yticks([])
# plt.show()
img=cv2.imread("imagelnm.jpg")
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh=cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
kernel=np.ones((3,3),np.uint8)
opening=cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel,iterations=2)
sure_bg=cv2.dilate(opening,kernel,iterations=3)
dist_transform=cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret,sure_fg=cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
sure_fg=np.uint8(sure_fg)
unknown=cv2.subtract(sure_bg,sure_fg)
ret,markers=cv2.connectedComponents(sure_fg)
markers=markers+1
markers[unknown==255]=0
markers=cv2.watershed(img,markers)
img[markers==-1]=[255,0,0]
plt.imshow(img)
plt.show()