# 工业器件检测和识别

---->

---->

```# -*- coding: utf-8 -*-

'''
plot： 实现图像中抠图，找到轮廓抠出来。
'''

import numpy as np
import cv2
import os

imgs = os.listdir(imgDir+imgFoldName)
imgNum = len(imgs)
data = []
label = []
for i in range (imgNum):
img_path = imgDir+imgFoldName+"/"+imgs[i]
data.append(img_path)
label.append(int(img_label))
return data,label

img_path = os.listdir(imgDir)
train_imgs = []
train_labels = []
for i, path in enumerate(img_path):
craterDir = imgDir + '/'
foldName = path
data, label = load_img_path(craterDir,foldName, i)
train_imgs.extend(data)
train_labels.extend(label)
#打乱数据集
index = [i for i in range(len(train_imgs))]
np.random.shuffle(index)
train_imgs = np.asarray(train_imgs)
train_labels = np.asarray(train_labels)
train_imgs = train_imgs[index]
train_labels = train_labels[index]
return train_imgs, train_labels

def plot(img_path):

#img = cv2.resize(img, (200, 100))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 直方图均衡化
eq = cv2.equalizeHist(gray)
# 中通滤波
b = cv2.medianBlur(eq, 9)

m, n = img.shape[:2]
b2 = cv2.resize(b, (n//4, m//4))
# 开运算和闭运算
m1 = cv2.morphologyEx(b2, cv2.MORPH_OPEN, np.ones((100, 100)))
m2 = cv2.morphologyEx(m1, cv2.MORPH_CLOSE, np.ones((4, 4)))

_, bw = cv2.threshold(m2, 150, 200, cv2.THRESH_BINARY_INV)

bw = cv2.resize(bw, (n, m))

r = img.copy()
# img2, ctrs, hier = cv2.findContours(bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 二值化，找轮廓。
img2, ctrs, hier = cv2.findContours( bw, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

min_area = 999999
c_min = 0
for ctr in ctrs:
area = cv2.contourArea(ctr)
if (area < min_area):
min_area = area
c_min = ctr
x, y, w, h = cv2.boundingRect(c_min)
# x, y, w, h = x-100, y-50, w+100, h+100
x, y, w, h = x-110, y-60, w+110, h+110
imgs = r[y:y+h, x:x+w]
#cv2.rectangle(r, (x, y), (x+w, y+h), (0, 255, 0), 10)
#cv2.imwrite("img.jpg", r)
cv2.imwrite("temp.jpg", imgs)
return imgs

def test(img_path):
image = plot(img_path)

def test_batch():
dir = 'train'
print (img_path)
img_number = len(img_path)
for i in range(img_number):
img_dir = img_path[i]
# print (img_dir)
image = plot(img_dir)
img_dir = img_dir.split('.')[0]
#save_path = 'train_aug/' + img_dir + str(0) + '.jpg'
save_path = 'train_aug/' + img_dir + str(1) + '.jpg'
print (save_path)
cv2.imwrite(save_path, image)

if __name__ == '__main__':
# test('lp.jpg')
test_batch()```

145 篇文章53 人订阅

0 条评论

## 相关文章

### 关于写论文说来简单但做起来难的三条建议

A few years ago, we prepared a series of workshops on writing research papers an...

29450

18740

### ffmpeg中avframe的YUV格式数据到OpenCV中Mat的BGR格式转换

ffmpeg实现音视频编解码是非常常用的工具，视频解码出来的raw数据是yuv格式，用来进行后续的图像处理一般是RGB格式的。所以需要从yuv到rgb或者bgr...

48590

23320

### 教程 | OpenCV深度神经网络实现人体姿态评估

OpenCV自从发布了DNN模块之后，就开始以开挂的方式支持各种深度学习预训练模型的调用，DNN模块的全称为深度神经网络，但是并不是所有深度学习模型导出到Ope...

29320

52240

27990

### 使用ESTIMATE来对转录组表达数据根据stromal和immune细胞比例估算肿瘤纯度

ESTIMATE (Estimation of STromal and Immune cells in MAlignant Tumor tissues usin...

55120

### 简单的验证码识别（opecv）

opencv版本： 3.0.0            处理验证码： 纯数字验证码 （颜色不同，有噪音，和带有较多的划痕）             ...

49260

1.5K10