源码:https://github.com/balancap/SSD-Tensorflow
1. 下载anaconda
2. 安装,记得勾上默认添加环境变量
3. 修改镜像源
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --set show_channel_urls yes
如果清华镜像源出现问题,换其他源。
4. 创建虚拟环境
conda create -n py3 python=3.6
5. 若是出现问题,恢复默认源:
conda config --remove-key channels
6. 激活虚拟环境,安装spyder
和jupyter notebook
:
conda install spyder
conda install notebook
7. 在虚拟环境中安装模块cv2
:
要安装opencv3
:
conda install --channel https://conda.anaconda.org/menpo opencv3
下面会安装的是opencv-python 4
:
pip install opencv-python
如果出现问题不能安装,可能是镜像源的问题,换一个源试试:
pip install opencv-python -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
8. 运行sea-land.py
,进行海陆分割:
import cv2
import os
# 定义海陆分离函数
import cv2
import os
# 定义海陆分离函数
def segmentFunc(img):
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 一、高斯滤波 滤波之后001159效果不佳
#blur = cv2.GaussianBlur(gray_img, (5, 5), 0)
# 二、otsu阈值
(t, thresh) = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# 三、形态学操作
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# 四、彩色图像的otsu分割
# 1.颜色空间转换:BGR转RGB
#result = cv2.cvtColor(cv2.bitwise_and(img, img, mask=thresh), cv2.COLOR_BGR2RGB)
result = cv2.bitwise_and(img, img, mask=thresh)
# 2.保存otsu分割的彩色照片
#cv2.imwrite("H:/wj/pictures/001159_otsu.jpg", result)
# 五、去除小连通域和大连通域
h, w, _ = result.shape
# 1.找到边界
# opencv版本不同,cv2.findContours返回值不同
# contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# 2.需要搞一个list给cv2.drawContours()
c_max = []
for i in range(len(contours)):
cnt = contours[i]
area = cv2.contourArea(cnt)
# 3.处理掉小区域和大区域
if(area < (h/50 * w/50)):
c_min = []
c_min.append(cnt)
# thickness不为-1时,表示画轮廓线,thickness的值表示线的宽度。
cv2.drawContours(thresh, c_min, -1, (0, 0, 0), thickness=-1)
continue
c_max.append(cnt)
cv2.drawContours(thresh, c_max, -1, (255, 255, 255), thickness=-1)
# 4.保存去除小连通域和大连通域的二值化图片
#cv2.imwrite("H:/wj/pictures/001159_area.jpg", thresh)
# 六、将彩色图片去除小连通域和大连通域
final = cv2.bitwise_and(result, result, mask=thresh)
return final
# 定义批量处理图片函数
def imgs_Process(filePath):
for filename in os.listdir(filePath):
img = cv2.imread(filePath + "/" + filename)
final = segmentFunc(img)
path = os.path.dirname(filePath) + "/result"
if os.path.exists(path) == False:
os.makedirs(path)
cv2.imwrite(path + "/" + filename, final)
# 主函数测试
if __name__ == "__main__":
# imgs_Process("H:/wj/pictures")
imgs_Process("F:/wj/pictures")
9. 安装tensorflow 1.14
用pip
安装tensorflow-cpu
,降级numpy
pip install tensorflow-cpu==1.14.0 -i https://pypi.mirrors.ustc.edu.cn/simple
pip uninstall numpy
pip install numpy==1.16.4
10. 运行ssd_notebook.ipynb
无法处理jpg
图片,需安装pillow
。
pip install -i https://pypi.doubanio.com/simple/ --trusted-host pypi.doubanio.com pillow