Hello Mat

 找回密码
 立即注册
查看: 7433|回复: 5

钢铁表面缺陷检测

[复制链接]

1323

主题

1551

帖子

0

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22647
发表于 2020-5-27 23:02:42 | 显示全部楼层 |阅读模式
钢铁表面缺陷检测:
数据:https://www.kaggle.com/c/severstal-steel-defect-detection/data

  1. from pathlib import Path
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import cv2

  6. class RLE:
  7.     """
  8.     Encapsulates run-length-encoding functionality.
  9.     """

  10.     MASK_H = 256
  11.     MASK_W = 1600

  12.     @classmethod
  13.     def from_str(cls, s):
  14.         if s != s:
  15.             return cls()
  16.         list_ = [int(n) for n in s.split(' ')]
  17.         return cls.from_list(list_)

  18.     @classmethod
  19.     def from_mask(cls, mask):
  20.         pixels = mask.T.flatten()
  21.         pixels = np.concatenate([[0], pixels, [0]])
  22.         runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
  23.         runs[1::2] -= runs[::2]
  24.         return cls.from_list(runs)

  25.     @classmethod
  26.     def from_list(cls, list_):
  27.         n_items = int(len(list_) / 2)
  28.         items = np.zeros((n_items, 2), dtype=np.uint64)
  29.         for i in range(n_items):
  30.             items[i, 0] = list_[i * 2]
  31.             items[i, 1] = list_[i * 2 + 1]
  32.         return cls(items)

  33.     def __init__(self, items=np.zeros((0, 0))):
  34.         self._items = items

  35.     @property
  36.     def items(self):
  37.         return self._items

  38.     def __iter__(self):
  39.         for idx, item in enumerate(self.items):
  40.             yield (item[0], item[1])  # run, length

  41.     def __len__(self):
  42.         return self.items.shape[0]

  43.     def to_mask(self):
  44.         mask = np.zeros(self.MASK_H * self.MASK_W, dtype=np.uint8)
  45.         for run, length in self:
  46.             run = int(run - 1)
  47.             end = int(run + length)
  48.             mask[run:end] = 1
  49.         return mask.reshape(self.MASK_H, self.MASK_W, order='F')

  50.     def to_str_list(self):
  51.         list_ = []
  52.         for run, length in self:
  53.             list_.append(str(run))
  54.             list_.append(str(length))
  55.         return list_

  56.     def __str__(self):
  57.         if len(self) == 0:
  58.             return ''
  59.         return ' '.join(self.to_str_list())

  60.     def __repr__(self):
  61.         return self.__str__()
  62.    
  63. def make_mask(labels):
  64.     masks = np.zeros((256, 1600, 4), dtype=np.float32)
  65.     for c, label in enumerate(labels.values):
  66.         rle = RLE.from_str(label)
  67.         masks[:, :, c] = rle.to_mask()
  68.     return masks

  69. img_size = 256 * 1600

  70. train_csv = 'F:/sck/steel/train.csv'
  71. df = pd.read_csv(train_csv)
  72. df.head()
  73. N_CLASSES = 4
  74. rle_cols = [f'rle{i}' for i in range(N_CLASSES)]
  75. df['ImageId'], df['ClassId'] = zip(*df['ImageId_ClassId'].str.split('_'))
  76. df['ClassId'] = df['ClassId'].astype(int)
  77. df = df.pivot(index='ImageId', columns='ClassId', values='EncodedPixels')
  78. df.columns = rle_cols
  79. df['defects'] = df.count(axis=1)
  80. df = df.loc[df.defects > 0, :]
  81. df.head()

  82. r1 = df.loc['0007a71bf.jpg'][rle_cols]
  83. r1

  84. m1 = make_mask(r1)[:, :, 2]
  85. plt.imshow(m1)

  86. for i in range(len(df)):
  87.     name=df.index[i]
  88.     ri = df.loc[name][rle_cols]
  89.     mi = make_mask(ri)
  90.     cv2.imwrite('F:/sck/steel/fourclass/1/'+name[0:-4]+'.png', mi[:,:,0])
  91.     cv2.imwrite('F:/sck/steel/fourclass/2/'+name[0:-4]+'.png', mi[:,:,1])
  92.     cv2.imwrite('F:/sck/steel/fourclass/3/'+name[0:-4]+'.png', mi[:,:,2])
  93.     cv2.imwrite('F:/sck/steel/fourclass/4/'+name[0:-4]+'.png', mi[:,:,3])
  94.     if(mi[:,:,0].max()>1):
  95.         print('11')
  96.     if(mi[:,:,1].max()>1):
  97.         print('11')
  98.     if(mi[:,:,2].max()>1):
  99.         print('11')
复制代码

参考:【1】https://www.kaggle.com/lightforever/severstal-mlcomp-catalyst-infer-0-90672
【2】https://blog.csdn.net/HRLSW/article/details/102779214
【3】AI Studio优质数据集
【4】https://aistudio.baidu.com/aistudio/datasetdetail/10941




算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Python|Opencv|MATLAB|Halcom.cn ( 蜀ICP备16027072号 )

GMT+8, 2024-11-22 16:52 , Processed in 0.214510 second(s), 24 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表