Skip to content

Commit

Permalink
dots lines result
Browse files Browse the repository at this point in the history
  • Loading branch information
luoolu committed Apr 15, 2020
1 parent 04d2bc5 commit 31a8123
Show file tree
Hide file tree
Showing 675 changed files with 726 additions and 116 deletions.
6 changes: 3 additions & 3 deletions Edge/canny_Edge_Detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
from matplotlib import pyplot as plt


img = cv.imread('data/bp_src3/5.jpg', 0)
edges = cv.Canny(img, 720, 576, edges=200, apertureSize=7)
img = cv.imread('/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/color/lb_color.png', 0)
edges = cv.Canny(img, 1001, 1001, edges=200, apertureSize=7)
edges = Image.fromarray(edges)
edges = edges.convert('RGBA')
data = np.array(edges) # "data" is a height x width x 4 numpy array
Expand All @@ -25,6 +25,6 @@
# data[..., :-1][white_areas.T] = (0, 136, 126) # Transpose back needed

im2 = Image.fromarray(data)
im2.save("data/temp/edge_ct.png")
im2.save("/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/edge/edge_lb.png")
im2.show()

4 changes: 2 additions & 2 deletions Transparent/batch_transparent_color.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@


if __name__ == '__main__':
for filename in glob.glob('/home/luolu/PycharmProjects/color_detection/data/result_qaak/caolv_mask/*.png'):
for filename in glob.glob('/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/edge/*.png'):
img = cv.imread(filename)
# print(filename)
base_name = os.path.basename(filename)
Expand All @@ -42,4 +42,4 @@
print(item)

img.putdata(newData)
img.save("/home/luolu/PycharmProjects/color_detection/data/result_qaak/transparent/" + base_name)
img.save("/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/trans/" + base_name)
4 changes: 2 additions & 2 deletions Transparent/color_img_transparent.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from PIL import Image

img = Image.open('/home/luolu/PycharmProjects/ParticleDetection/data/image/line_thresh_pills_02.png')
img = Image.open('/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/color/fen_color.png')
img = img.convert("RGBA")
datas = img.getdata()

Expand All @@ -25,4 +25,4 @@


img.putdata(newData)
img.save("/home/luolu/PycharmProjects/ParticleDetection/data/image/trans_line_thresh_pills_02.png", "PNG")
img.save("/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/trans/fen_color.png", "PNG")
41 changes: 41 additions & 0 deletions batch_fill_hole.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# -*- coding: utf-8 -*-
# @Time : 2020/4/14 上午10:07
# @Author : LuoLu
# @FileName: batch_fill_hole.py
# @Software: PyCharm
# @Github :https://github.com/luolugithub
# @E-mail :[email protected]
import glob
import os

import cv2 as cv
import numpy as np

root_path = '/home/luolu/PycharmProjects/ParticleDetection/'

if __name__ == '__main__':
base_name = ''
counter = 0
for filename in glob.glob('data/yashi_qscan/mask/*.png'):
img = cv.imread(filename, 0)
# height, width, channels = img.shape
print(filename)
base_name = os.path.basename(filename)
save_name = base_name.split('_')[0]

# fill hole
# read image, ensure binary
img[img != 0] = 255

# flood fill background to find inner holes
holes = img.copy()
cv.floodFill(holes, None, (0, 0), 255)

# invert holes mask, bitwise or with img fill in holes
holes = cv.bitwise_not(holes)
filled_holes = cv.bitwise_or(img, holes)

cv.imwrite(root_path + "data/yashi_qscan/" + save_name + '.png', filled_holes)
counter = counter + 1

print('counter: ', counter)
63 changes: 63 additions & 0 deletions batch_remove_small.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
# @Time : 2020/4/14 下午4:13
# @Author : LuoLu
# @FileName: batch_remove_small.py
# @Software: PyCharm
# @Github :https://github.com/luolugithub
# @E-mail :[email protected]

import glob
import os

import cv2 as cv
import numpy as np

root_path = '/home/luolu/PycharmProjects/ParticleDetection/'

if __name__ == '__main__':
base_name = ''
counter = 0
for filename in glob.glob('data/yashi_qscan/mask/*.png'):
img = cv.imread(filename, 0)
# height, width, channels = img.shape
print(filename)
base_name = os.path.basename(filename)
save_name = base_name.split('_')[0]

# fill hole
# read image, ensure binary
img[img != 0] = 255

# flood fill background to find inner holes
holes = img.copy()
cv.floodFill(holes, None, (0, 0), 255)

# invert holes mask, bitwise or with img fill in holes
holes = cv.bitwise_not(holes)
filled_holes = cv.bitwise_or(img, holes)

# remove_small_objects

# find all your connected components (white blobs in your image)
nb_components, output, stats, centroids = cv.connectedComponentsWithStats(filled_holes, connectivity=8)
# connectedComponentswithStats yields every seperated component with information on each of them,
# such as size the following part is just taking out the background which is also considered a component,
# but most of the time we don't want that.
sizes = stats[1:, -1]
nb_components = nb_components - 1

# minimum size of particles we want to keep (number of pixels)
# here, it's a fixed value, but you can set it as you want, eg the mean of the sizes or whatever
min_size = 250

# your answer image
cleaned = np.zeros((output.shape))
# for every component in the image, you keep it only if it's above min_size
for i in range(0, nb_components):
if sizes[i] >= min_size:
cleaned[output == i + 1] = 255

cv.imwrite(root_path + "data/yashi_qscan/cleaned/" + save_name + '.png', cleaned)
counter = counter + 1

print('counter: ', counter)
6 changes: 3 additions & 3 deletions binary_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,20 @@
from PIL.Image import Image


path = "/home/luolu/PycharmProjects/ParticleDetection/data/image/particle_ct.png"
path = "/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/color/fen_color.png"
original = cv.imread(path)
height, width, channels = original.shape
src = cv.GaussianBlur(original, (1, 1), 0)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
# cv.THRESH_BINARY | cv.THRESH_OTSU "ct.png"
ret, binary_ = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TOZERO)
ret, binary_ = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)

# 使用开运算去掉外部的噪声
# kernel = cv.getStructuringElement(cv.MORPH_RECT, (11, 11))
# binary = cv.morphologyEx(binary_, cv.MORPH_OPEN, kernel)
cv.imshow('binary', binary_)

cv.imwrite("/home/luolu/PycharmProjects/ParticleDetection/data/image/binary_ct.png", binary_)
# cv.imwrite("/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/binary_test.png", binary_)

cv.waitKey(0)
cv.destroyAllWindows()
2 changes: 1 addition & 1 deletion blob_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
# Show blobs
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey(0)

cv2.destroyAllWindows()

# detector = cv2.SimpleBlobDetector()
#
Expand Down
Binary file added bmjs.ttf
Binary file not shown.
60 changes: 60 additions & 0 deletions conncted_components.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
# @Time : 2020/4/8 上午10:52
# @Author : LuoLu
# @FileName: conncted_components.py
# @Software: PyCharm
# @Github :https://github.com/luolugithub
# @E-mail :[email protected]

import cv2
import numpy as np
from PIL import Image
from collections import Counter

img = cv2.imread('/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/edge/edge_cl.png', 0)
img = cv2.GaussianBlur(img, (1, 1), 0)
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary
num_labels, labels_im = cv2.connectedComponents(img)
print("num_labels:", num_labels - 1)
# Image._show(Image.fromarray(labels_im == 2), title="labels_im.jpg")
print("len labels_im:", (labels_im == 2).shape)
print("type labels_im:", type(labels_im))
# print("len 1:", np.where((labels_im == 2).sum()))
# count = [0] * (num_labels)
# print("count len:", range(num_labels))
# for num in range(1, num_labels, 1):
# for i in range((labels_im == num).shape[0]):
# for j in range((labels_im == num).shape[1]):
# if (labels_im == num)[i][j] == 1:
# count[num] = count[num] + 1
#
# print("count len:", len(count))
# for iterm in range(1, len(count), 1):
# print("iterm" + str(iterm) + ":", count[iterm])





def imshow_components(labels):
# Map component labels to hue val
label_hue = np.uint8(179 * labels / np.max(labels))
# Image._show(Image.fromarray(label_hue), title="label_hue.jpg")

blank_ch = 255 * np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

# cvt to BGR for display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
# Image._show(Image.fromarray(blank_ch), title="blank_ch.jpg")

# set bg label to black
labeled_img[label_hue == 0] = 40

cv2.namedWindow("labeled", flags=2)
cv2.imshow("labeled", labeled_img)
cv2.waitKey(0)
cv2.destroyAllWindows()


imshow_components(labels_im)
92 changes: 92 additions & 0 deletions count/count_mask.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*-
# @Time : 2020/3/23 下午4:30
# @Author : LuoLu
# @FileName: count_mask.py
# @Software: PyCharm
# @Github :https://github.com/luolugithub
# @E-mail :[email protected]
import cv2
import matplotlib
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from PIL.Image import Image

matplotlib.use('TkAgg')
cv.namedWindow("original", flags=2)
cv.namedWindow("binary", flags=2)
cv.namedWindow("colored labels", flags=2)

path = "/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/edge/edge_cl.png"
# img_src = "/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/binary_test.png"
original = cv.imread(path)
# src_image = cv.imread(img_src)
height, width, channels = original.shape
src = cv.GaussianBlur(original, (3, 3), 0)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
ret, binary_ = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)

# 使用开运算去掉外部的噪声
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
binary = cv.morphologyEx(binary_, cv.MORPH_OPEN, kernel)
# gray_correct = np.array(255 * (gray / 255) ** 1.2, dtype='uint8')
# thresh = cv.adaptiveThreshold(gray_correct, 50, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 255, 50)
# binary = cv.bitwise_not(thresh)
cv.imshow("original", original)
cv.imshow("binary", binary_)
# cv.imshow("binary digit", binary_)

num_labels, labels, stats, centers = cv.connectedComponentsWithStats(binary, connectivity=4, ltype=cv.CV_32S)
colors = []
for i in range(num_labels):
b = np.random.randint(0, 256)
g = np.random.randint(0, 256)
r = np.random.randint(0, 256)
colors.append((b, g, r))

# add continuous pixel count
img = cv2.imread(path, 0)
img = cv2.GaussianBlur(img, (1, 1), 0)
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary
num_labels_original, labels_im = cv2.connectedComponents(img)
count = [0] * (num_labels_original)
# print("count len:", range(1, num_labels_original, 1))
# for num in range(num_labels_original):
# for i in range((labels_im == num).shape[0]):
# for j in range((labels_im == num).shape[1]):
# if (labels_im == num)[i][j] == 1:
# count[num] = count[num] + 1
#
# dots = 0
# line = 0
# for iterm in range(1, len(count), 1):
# # print("iterm" + str(iterm) + ":", count[iterm])
# if count[iterm] > 10:
# line = line + 1
# else:
# dots = dots + 1

colors[0] = (0, 0, 0)
image = np.copy(src)
for t in range(1, num_labels, 1):
x, y, w, h, area = stats[t]
cx, cy = centers[t]
# 标出中心位置
# cv.circle(src_image, (np.int32(cx), np.int32(cy)), 1, (255, 0, 0), 0, 1, 0)
# 画出外接矩形
cv.rectangle(image, (x, y), (x + w, y + h), colors[t], 1, 8, 0)
# cv.putText(src_image, str(t).__add__(":L=").__add__(str(count[t])), (x, y), cv.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 255), 1)
cv.putText(image, str(t), (x, y), cv.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 255), 1)
print("label index %d, area of the label : %d" % (t, area))

cv.imshow("colored labels", image)
# cv.imwrite("labels.png", image)
print("total number : ", num_labels - 1)
cv.putText(image, "contact Sum:" + str(num_labels - 1), (30, 960), cv.FONT_HERSHEY_SIMPLEX, .8, (0, 0, 255), 3)
# cv.putText(src_image, "dots:" + str(dots), (30, 300), cv.FONT_HERSHEY_SIMPLEX, .8, (0, 0, 255), 2)
# cv.putText(src_image, "lines:" + str(line), (30, 330), cv.FONT_HERSHEY_SIMPLEX, .8, (0, 0, 255), 2)

# input = cv.imread("granule.png")
# connected_components_stats_demo(input)
cv.waitKey(0)
cv.destroyAllWindows()
43 changes: 43 additions & 0 deletions count/length_contact.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
# @Time : 2020/4/15 上午10:38
# @Author : LuoLu
# @FileName: length_contact.py
# @Software: PyCharm
# @Github :https://github.com/luolugithub
# @E-mail :[email protected]

import numpy as np
import cv2 as cv

img = cv.imread('/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/contact_test.png')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 0, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
num_labels, labels_im = cv.connectedComponents(thresh)
print("num_labels:", num_labels - 1)
print("len contours :", len(contours))
count0 = 0

dots = 0
line = 0

for iterm in range(len(contours)):
len_contact = cv.arcLength(contours[iterm], False)
print("iterm:" + str(iterm) + "," + "perimeter = " + str(len_contact))
if len_contact != 0:
if len_contact > 30:
line = line + 1
else:
dots = dots + 1
# print("count0 contours :", count0)
# print("jian :", len(contours) - count0)
print("dots :", dots)
print("line :", line)
print(type(img))
img = np.copy(img)
cv.putText(img, "dots Sum:" + str(dots), (30, 960), cv.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 255), 1)
cv.putText(img, "line Sum:" + str(line), (30, 990), cv.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 255), 1)
cv.imwrite("/home/luolu/PycharmProjects/ParticleDetection/data/yashi_qscan/perimeter/result_contact.png", img)
cv.imshow("img", img)
cv.waitKey()
cv.destroyAllWindows()
Loading

0 comments on commit 31a8123

Please sign in to comment.