当前位置:   article > 正文

opencv 截图leiding_cv2.sobel(img, cv2.cv_16sc1, 1, 0)

cv2.sobel(img, cv2.cv_16sc1, 1, 0)

opencv 这个效果差一点

  1. import cv2
  2. import numpy as np
  3. import os
  4. import time
  5. GAUSSIAN_BLUR_KERNEL_SIZE=(5,5)
  6. GAUSSIAN_BLUR_SIGMA_X=0
  7. CANNY_THRESHOLD1=60
  8. CANNY_THRESHOLD2=250
  9. LEEXING=4
  10. def get_gaussian_blur_image(image):
  11. return cv2.GaussianBlur(image,GAUSSIAN_BLUR_KERNEL_SIZE,GAUSSIAN_BLUR_SIGMA_X)
  12. def get_canny_image(image):
  13. return cv2.Canny(image,CANNY_THRESHOLD1,CANNY_THRESHOLD2)
  14. def get_contours(image):
  15. contours,_=cv2.findContours(image,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
  16. return contours
  17. def lp(imgsss):
  18. img1=cv2.imread(imgsss,0)
  19. x1=cv2.Sobel(img1,cv2.CV_16S,1,0,ksize=-1)
  20. y1=cv2.Sobel(img1,cv2.CV_16S,0,1,ksize=-1)
  21. Scale_absX1=cv2.convertScaleAbs(x1)
  22. Scale_absY1=cv2.convertScaleAbs(y1)
  23. result1=cv2.addWeighted(Scale_absX1,0.5,Scale_absY1,0.5,0)
  24. return result1
  25. def ceshi1(imgsss):
  26. image_raw = cv2.imread(imgsss)
  27. h, w, _ = image_raw.shape
  28. mianji_MIN1 = 15000
  29. mianji_MAX1 = 40000
  30. zhouchang_min = 80
  31. zhouchang_max = 1800
  32. offset_min = 0.5 * image_raw.shape[1]
  33. offset_max = 0.95 * image_raw.shape[1]
  34. result1 = lp(imgsss)
  35. # 高斯去噪
  36. result2 = get_gaussian_blur_image(result1)
  37. # 均值
  38. result3 = cv2.blur(result2, (3, 3))
  39. # 提取輪廓
  40. image_canny = get_canny_image(result3)
  41. # 膨脹
  42. kernel = np.ones((3, 3), np.uint8)
  43. dige_dilate1 = cv2.dilate(image_canny, kernel, iterations=1)
  44. # 中值
  45. median = cv2.medianBlur(dige_dilate1, 5)
  46. contours = get_contours(median)
  47. image = cv2.imread(imgsss)
  48. contour = image.copy()
  49. cv2.drawContours(contour, contours, -1, (0, 255, 0), 2)
  50. count = 0 # 个数
  51. margin = 5 # 裁剪边距
  52. draw_rect = image.copy()
  53. for i, contour in enumerate(contours):
  54. area = cv2.contourArea(contour) # 计算包围形状的面积
  55. zhouchang = cv2.arcLength(contour, True)
  56. x2, y2, w2, h2 = cv2.boundingRect(contour)
  57. if area < mianji_MIN1: # 过滤面积小于15的形状
  58. continue
  59. if area > mianji_MAX1: # 过滤面积小于15的形状
  60. continue
  61. if zhouchang < zhouchang_min:
  62. continue
  63. if zhouchang > zhouchang_max:
  64. continue
  65. if x2 < offset_min:
  66. continue
  67. if x2 > offset_max:
  68. continue
  69. print('面積:', area, '周長:', zhouchang)
  70. count += 1
  71. rect = cv2.minAreaRect(contour) # 检测轮廓最小外接矩形,得到最小外接矩形的(中心(x,y), (宽,高), 旋转角度)
  72. box = np.int0(cv2.boxPoints(rect)) # 获取最小外接矩形的4个顶点坐标
  73. print(box)
  74. txt11=txt1(q=box,width=w,height=h)
  75. txt22=str(LEEXING)+' '+str(txt11[0])+' '+str(txt11[1])+' '+str(txt11[2])+' '+str(txt11[3])
  76. print(txt22)
  77. cv2.drawContours(draw_rect, [box], 0, (0, 0, 255), 2) # 绘制轮廓最小外接矩形
  78. h, w = image.shape[:2] # 原图像的高和宽
  79. rect_w, rect_h = int(rect[1][0]) + 1, int(rect[1][1]) + 1 # 最小外接矩形的宽和高
  80. if rect_w <= rect_h:
  81. x, y = int(box[1][0]), int(box[1][1]) # 旋转中心
  82. M2 = cv2.getRotationMatrix2D((x, y), rect[2], 1)
  83. rotated_image = cv2.warpAffine(image, M2, (w * 2, h * 2))
  84. y1, y2 = y - margin if y - margin > 0 else 0, y + rect_h + margin + 1
  85. x1, x2 = x - margin if x - margin > 0 else 0, x + rect_w + margin + 1
  86. rotated_canvas = rotated_image[y1: y2, x1: x2]
  87. else:
  88. x, y = int(box[2][0]), int(box[2][1]) # 旋转中心
  89. M2 = cv2.getRotationMatrix2D((x, y), rect[2] + 90, 1)
  90. rotated_image = cv2.warpAffine(image, M2, (w * 2, h * 2))
  91. y1, y2 = y - margin if y - margin > 0 else 0, y + rect_w + margin + 1
  92. x1, x2 = x - margin if x - margin > 0 else 0, x + rect_h + margin + 1
  93. rotated_canvas = rotated_image[y1: y2, x1: x2]
  94. print("rice #{}".format(count))
  95. # cv2.imshow("rotated_canvas", rotated_canvas)
  96. imgs = imgsss.split('\\')
  97. cv2.imwrite("./imgs/{}.jpg".format(imgs[-1]+str(count)), rotated_canvas)
  98. with open("./imgs/{}.txt".format(imgs[-1]+str(count)), 'w') as fp:
  99. fp.write(txt22)
  100. cv2.waitKey(0)
  101. cv2.imwrite("rect.jpg", draw_rect)
  102. def wenjian(path1):
  103. df_list=[]
  104. list212=os.listdir(path1)
  105. for i in list212:
  106. file_path=os.path.join(path1,i)
  107. df_list.append(file_path)
  108. return df_list
  109. def txt1(q,width,height):
  110. x1=q[1][0]
  111. x2=q[3][0]
  112. y1=q[1][1]
  113. y2=q[3][1]
  114. xmin_xishu, xmax_xishu =x1 / width, x2 / width
  115. ymin_xishu, ymax_xishu= y1 / height ,y2 / height
  116. width2=xmax_xishu-xmin_xishu
  117. height2=ymax_xishu-ymin_xishu
  118. x_centr_shu=xmin_xishu+width2/2
  119. y_centr_shu=ymin_xishu+height2/2
  120. return round(x_centr_shu, 6),round(y_centr_shu, 6),round(width2, 6),round(height2, 6)
  121. if __name__ == '__main__':
  122. a=time.time()
  123. path1 = r'E:\0908\1WVE' # 路径
  124. list1=wenjian(path1)
  125. for i in list1:
  126. ceshi1(i)
  127. b=time.time()
  128. c=b-a
  129. print(c)

 这个效果可以

  1. import cv2
  2. import numpy as np
  3. import os
  4. import time
  5. GAUSSIAN_BLUR_KERNEL_SIZE=(5,5)
  6. GAUSSIAN_BLUR_SIGMA_X=0
  7. CANNY_THRESHOLD1=120
  8. CANNY_THRESHOLD2=250
  9. LEEXING=12 #要识别的类
  10. def get_gaussian_blur_image(image): #高斯去噪
  11. return cv2.GaussianBlur(image,GAUSSIAN_BLUR_KERNEL_SIZE,GAUSSIAN_BLUR_SIGMA_X)
  12. def get_canny_image(image): #找轮廓
  13. return cv2.Canny(image,CANNY_THRESHOLD1,CANNY_THRESHOLD2)
  14. def get_contours(image): #导出轮廓参数
  15. contours,_=cv2.findContours(image,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
  16. return contours
  17. def lp(imgsss): #算轮廓
  18. img1=cv2.imread(imgsss,0)
  19. x1=cv2.Sobel(img1,cv2.CV_16S,1,0,ksize=-1)
  20. y1=cv2.Sobel(img1,cv2.CV_16S,0,1,ksize=-1)
  21. Scale_absX1=cv2.convertScaleAbs(x1)
  22. Scale_absY1=cv2.convertScaleAbs(y1)
  23. result1=cv2.addWeighted(Scale_absX1,0.5,Scale_absY1,0.5,0)
  24. return result1
  25. def ceshi1(imgsss):
  26. image_raw = cv2.imread(imgsss)
  27. h, w, _ = image_raw.shape
  28. mianji_MIN1 = 700000 #最小面积
  29. mianji_MAX1 = 1000000 #3最大面积
  30. zhouchang_min = 3000 #最小周长
  31. zhouchang_max = 5000 最大周长
  32. offset_min = 0.4 * image_raw.shape[1] #最小偏移量
  33. offset_max = 0.99 * image_raw.shape[1] #最大偏移量
  34. img = cv2.imread(imgsss)
  35. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #一个算子也可以改改成lp函数里的算子
  36. blurred = cv2.GaussianBlur(gray, (3, 3), 0)
  37. xgrad = cv2.Sobel(blurred, cv2.CV_16SC1, 1, 0)
  38. ygrad = cv2.Sobel(blurred, cv2.CV_16SC1, 0, 1)
  39. edge_output = cv2.Canny(xgrad, ygrad, 50, 150)
  40. rect_Kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
  41. image_tophat = cv2.morphologyEx(edge_output, cv2.MORPH_CLOSE, rect_Kernel)
  42. contours = get_contours(image_tophat)
  43. image = cv2.imread(imgsss)
  44. contour = image.copy()
  45. cv2.drawContours(contour, contours, -1, (0, 255, 0), 2)
  46. count = 0 # 个数
  47. margin = 5 # 裁剪边距
  48. draw_rect = image.copy()
  49. for i, contour in enumerate(contours):
  50. area = cv2.contourArea(contour) # 计算包围形状的面积
  51. zhouchang = cv2.arcLength(contour, True)
  52. x2, y2, w2, h2 = cv2.boundingRect(contour)
  53. if area < mianji_MIN1: # 过滤面积小于15的形状
  54. continue
  55. if area > mianji_MAX1: # 过滤面积小于15的形状
  56. continue
  57. if zhouchang < zhouchang_min:
  58. continue
  59. if zhouchang > zhouchang_max:
  60. continue
  61. if x2 < offset_min:
  62. continue
  63. if x2 > offset_max:
  64. continue
  65. print('面積:', area, '周長:', zhouchang)
  66. count += 1
  67. rect = cv2.minAreaRect(contour) # 检测轮廓最小外接矩形,得到最小外接矩形的(中心(x,y), (宽,高), 旋转角度)
  68. box = np.int0(cv2.boxPoints(rect)) # 获取最小外接矩形的4个顶点坐标
  69. # print(box)
  70. txt11=txt1(q=box,width=w,height=h)
  71. txt22=str(LEEXING)+' '+str(txt11[0])+' '+str(txt11[1])+' '+str(txt11[2])+' '+str(txt11[3])
  72. print(txt22)
  73. cv2.drawContours(draw_rect, [box], 0, (0, 0, 255), 2) # 绘制轮廓最小外接矩形
  74. h, w = image.shape[:2] # 原图像的高和宽
  75. rect_w, rect_h = int(rect[1][0]) + 1, int(rect[1][1]) + 1 # 最小外接矩形的宽和高
  76. if rect_w <= rect_h:
  77. x, y = int(box[1][0]), int(box[1][1]) # 旋转中心
  78. M2 = cv2.getRotationMatrix2D((x, y), rect[2], 1)
  79. rotated_image = cv2.warpAffine(image, M2, (w * 2, h * 2))
  80. y1, y2 = y - margin if y - margin > 0 else 0, y + rect_h + margin + 1
  81. x1, x2 = x - margin if x - margin > 0 else 0, x + rect_w + margin + 1
  82. rotated_canvas = rotated_image[y1: y2, x1: x2]
  83. else:
  84. x, y = int(box[2][0]), int(box[2][1]) # 旋转中心
  85. M2 = cv2.getRotationMatrix2D((x, y), rect[2] + 90, 1)
  86. rotated_image = cv2.warpAffine(image, M2, (w * 2, h * 2))
  87. y1, y2 = y - margin if y - margin > 0 else 0, y + rect_w + margin + 1
  88. x1, x2 = x - margin if x - margin > 0 else 0, x + rect_h + margin + 1
  89. rotated_canvas = rotated_image[y1: y2, x1: x2]
  90. print("rice #{}".format(count))
  91. # cv2.imshow("rotated_canvas", rotated_canvas)
  92. imgs = imgsss.split('\\')
  93. cv2.imwrite("./imgs/{}.jpg".format(imgs[-1]+str(count)), rotated_canvas)
  94. with open("./imgs/{}.txt".format(imgs[-1]+str(count)), 'w') as fp:
  95. fp.write(txt22)
  96. cv2.waitKey(0)
  97. cv2.imwrite("./imgs/{}.png".format(imgs[-1]+str(count)), draw_rect)
  98. # cv2.imwrite("rect.jpg", draw_rect)
  99. def wenjian(path1):
  100. df_list=[] #读取文件夹里的照片
  101. list212=os.listdir(path1)
  102. for i in list212:
  103. file_path=os.path.join(path1,i)
  104. df_list.append(file_path)
  105. return df_list
  106. def txt1(q,width,height): #计算出需要的参数
  107. x1=q[1][0]
  108. x2=q[3][0]
  109. y1=q[1][1]
  110. y2=q[3][1]
  111. xmin_xishu, xmax_xishu =x1 / width, x2 / width
  112. ymin_xishu, ymax_xishu= y1 / height ,y2 / height
  113. width2=xmax_xishu-xmin_xishu
  114. height2=ymax_xishu-ymin_xishu
  115. x_centr_shu=xmin_xishu+width2/2
  116. y_centr_shu=ymin_xishu+height2/2
  117. return round(x_centr_shu, 6),round(y_centr_shu, 6),round(width2, 6),round(height2, 6)
  118. if __name__ == '__main__':
  119. a=time.time()
  120. path1 = r'D:\AOI\18HP' # 路径
  121. list1=wenjian(path1)
  122. for i in list1:
  123. print(i)
  124. ceshi1(i)
  125. b=time.time()
  126. c=b-a
  127. print(c)

单独跑一张图片的

 

  1. import cv2 as cv
  2. import numpy as np
  3. import time
  4. from matplotlib import pyplot as plt
  5. # kernel = np.ones((3,3),np.uint8) #腐蝕
  6. # dige_erosion = cv.erode(image_canny,kernel,iterations = 1)
  7. #
  8. # kernel = np.ones((3,3),np.uint8) #膨脹
  9. # dige_dilate = cv.dilate(dige_erosion,kernel,iterations = 2)
  10. a=time.time()
  11. imgsss='1.jpg'
  12. CANNY_THRESHOLD1=60
  13. CANNY_THRESHOLD2=150
  14. GAUSSIAN_BLUR_KERNEL_SIZE=(5,5)
  15. GAUSSIAN_BLUR_SIGMA_X=0
  16. image_raw=cv.imread(imgsss)
  17. mianji_MIN1=700000
  18. mianji_MAX1=1000000
  19. zhouchang_min=3000
  20. zhouchang_max=5000
  21. offset_min=0.4*image_raw.shape[1]
  22. offset_max=0.99*image_raw.shape[1]
  23. #拉普算子
  24. def lp(imgsss):
  25. img1=cv.imread(imgsss,0)
  26. x1=cv.Sobel(img1,cv.CV_16S,1,0,ksize=-1)
  27. y1=cv.Sobel(img1,cv.CV_16S,0,1,ksize=-1)
  28. Scale_absX1=cv.convertScaleAbs(x1)
  29. Scale_absY1=cv.convertScaleAbs(y1)
  30. result1=cv.addWeighted(Scale_absX1,0.5,Scale_absY1,0.5,0)
  31. return result1
  32. def zhi():
  33. image = cv.imread(imgsss, cv.IMREAD_GRAYSCALE)
  34. thresh1 = cv.adaptiveThreshold(image, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2)
  35. thresh2 = cv.adaptiveThreshold(image, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV, 11, 2)
  36. thresh3 = cv.adaptiveThreshold(image, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2)
  37. thresh4 = cv.adaptiveThreshold(image, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY_INV, 11, 2)
  38. return thresh1,thresh2,thresh3,thresh4
  39. def erzhi():
  40. # 读取第一张图像
  41. img = cv.imread(imgsss)
  42. # 获取图像尺寸
  43. h, w = img.shape[0:2]
  44. # 自定义空白单通道图像,用于存放灰度图
  45. gray = np.zeros((h, w), dtype=img.dtype)
  46. # 对原图像进行遍历,然后分别对B\G\R按比例灰度化
  47. for i in range(h):
  48. for j in range(w):
  49. gray[i, j] = max(img[i, j, 0], img[i, j, 1], img[i, j, 2]) # 求3通道中最大的值
  50. gray = cv.cvtColor(gray, cv.COLOR_BGR2RGB) # BGR转换为RGB显示格式,方便通过matplotlib进行图像显示
  51. ref_BINARY = cv.threshold(gray, 180, 255, cv.THRESH_BINARY_INV)[1] # 转换成二值图像
  52. return ref_BINARY
  53. '''高斯去噪'''
  54. def get_gaussian_blur_image(image): #高斯去噪
  55. return cv.GaussianBlur(image,GAUSSIAN_BLUR_KERNEL_SIZE,GAUSSIAN_BLUR_SIGMA_X)
  56. def get_canny_image(image):
  57. return cv.Canny(image,CANNY_THRESHOLD1,CANNY_THRESHOLD2)
  58. def get_contours(image):
  59. contours,_=cv.findContours(image,cv.RETR_CCOMP,cv.CHAIN_APPROX_SIMPLE)
  60. return contours
  61. img = cv.imread(imgsss)
  62. gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
  63. blurred = cv.GaussianBlur(gray, (3, 3), 0)
  64. xgrad = cv.Sobel(blurred, cv.CV_16SC1, 1, 0)
  65. ygrad = cv.Sobel(blurred, cv.CV_16SC1, 0, 1)
  66. edge_output = cv.Canny(xgrad, ygrad, 50, 150)
  67. rect_Kernel = cv.getStructuringElement(cv.MORPH_RECT, (9, 3))
  68. image_tophat = cv.morphologyEx(edge_output, cv.MORPH_CLOSE, rect_Kernel)
  69. # #高斯去噪
  70. # result2=get_gaussian_blur_image(result1)
  71. # #均值
  72. # result3 = cv.blur(result2,(3,3))
  73. #提取輪廓
  74. # image_canny=get_canny_image(s1)
  75. #膨脹
  76. # kernel = np.ones((3,3),np.uint8)
  77. # dige_dilate1 = cv.dilate(image_canny,kernel,iterations = 1)
  78. #中值
  79. # median = cv.medianBlur(image_canny,5)
  80. contours=get_contours(image_tophat)
  81. image = cv.imread(imgsss)
  82. contour = image.copy()
  83. cv.drawContours(contour, contours, -1, (0, 255, 0), 2)
  84. count = 0 # 个数
  85. margin = 5 # 裁剪边距
  86. draw_rect = image.copy()
  87. for i, contour in enumerate(contours):
  88. area = cv.contourArea(contour) # 计算包围形状的面积
  89. zhouchang = cv.arcLength(contour, True)
  90. x2,y2,w2,h2=cv.boundingRect(contour)
  91. if area < mianji_MIN1: # 过滤面积小于15的形状
  92. continue
  93. if area >mianji_MAX1: # 过滤面积小于15的形状
  94. continue
  95. if zhouchang<zhouchang_min:
  96. continue
  97. if zhouchang>zhouchang_max:
  98. continue
  99. if x2 < offset_min:
  100. continue
  101. if x2 > offset_max:
  102. continue
  103. print('面積:',area ,'周長:',zhouchang)
  104. count += 1
  105. rect = cv.minAreaRect(contour) # 检测轮廓最小外接矩形,得到最小外接矩形的(中心(x,y), (宽,高), 旋转角度)
  106. box = np.int0(cv.boxPoints(rect)) # 获取最小外接矩形的4个顶点坐标
  107. # print(box)
  108. cv.drawContours(draw_rect, [box], 0, (0, 0,255), 2) # 绘制轮廓最小外接矩形
  109. h, w = image.shape[:2] # 原图像的高和宽
  110. rect_w, rect_h = int(rect[1][0]) + 1, int(rect[1][1]) + 1 # 最小外接矩形的宽和高
  111. if rect_w <= rect_h:
  112. x, y = int(box[1][0]), int(box[1][1]) # 旋转中心
  113. M2 = cv.getRotationMatrix2D((x, y), rect[2], 1)
  114. rotated_image = cv.warpAffine(image, M2, (w * 2, h * 2))
  115. y1, y2 = y - margin if y - margin > 0 else 0, y + rect_h + margin + 1
  116. x1, x2 = x - margin if x - margin > 0 else 0, x + rect_w + margin + 1
  117. rotated_canvas = rotated_image[y1: y2, x1: x2]
  118. else:
  119. x, y = int(box[2][0]), int(box[2][1]) # 旋转中心
  120. M2 = cv.getRotationMatrix2D((x, y), rect[2] + 90, 1)
  121. rotated_image = cv.warpAffine(image, M2, (w * 2, h * 2))
  122. y1, y2 = y - margin if y - margin > 0 else 0, y + rect_w + margin + 1
  123. x1, x2 = x - margin if x - margin > 0 else 0, x + rect_h + margin + 1
  124. rotated_canvas = rotated_image[y1: y2, x1: x2]
  125. print("rice #{}".format(count))
  126. # cv2.imshow("rotated_canvas", rotated_canvas)
  127. cv.imwrite("./imgs/{}.jpg".format(count), rotated_canvas)
  128. cv.waitKey(0)
  129. cv.imwrite("rect.jpg", draw_rect)
  130. b=time.time()
  131. c=b-a
  132. print(c)
  133. plt.figure()
  134. plt.imshow(image_tophat)
  135. plt.title("space")
  136. plt.show()

Opencv图像处理(全)_胖墩会武术的博客-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/148813
推荐阅读
相关标签
  

闽ICP备14008679号