PIL使用笛卡尔像素坐标系统,坐标(0,0)位于左上角。注意:坐标值表示像素的角;位于坐标(0,0)处的像素的中心实际上位于(0.5,0.5)。坐标经常用于二元组(x,y)。长方形则表示为四元组,前面是左上角坐标。例如:一个覆盖800x600的像素图像的长方形表示为(0,0,800,600)。
cropped = img.crop((left, upper, right, lower))#PIL裁剪图片实际上是左上角点(left, upper)与右下角点坐标(right, lower)
matplot默认使用笛卡尔像素坐标系统,坐标(0,0)位于左上角。但是matplot会自动添加白色边框
# -*- coding: utf-8 -*- """ Created on Tue Mar 05 16:21:01 2019 @author: Manuel """ import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from skimage import data,filters,segmentation,measure,morphology,color from scipy.misc import imread from PIL import Image #加载并裁剪硬币图片 image =color.rgb2gray(imread("1551254703(1).jpg"))#data.coins()[50:-50, 50:-50]#返回一个数组 thresh=filters.threshold_otsu(image) #阈值分割,自动返回一个阈值 bw =morphology.closing(image>thresh,morphology.square(3))#(image > thresh, morphology.square(3)) #闭运算#将0,1转换成bool #print(bw) cleared = bw.copy() #复制 #print(cleared) segmentation.clear_border(cleared) #清除与边界相连的目标物 label_image =measure.label(cleared) #连通区域标记 borders = np.logical_xor(bw, cleared) #逻辑异或 label_image[borders] = -1 #? image_label_overlay =color.label2rgb(label_image, image=image) #不同标记用不同颜色显示 #fig,(ax0)= plt.subplots(1, figsize=(8, 6)) fig,(ax1)= plt.subplots(1, figsize=(8, 6))#函数返回两个值,赋给fig和ax1 #fig,(ax0,ax1)= plt.subplots(1,2, figsize=(8, 6)) #ax0.imshow(cleared,plt.cm.gray) ax1.imshow(image_label_overlay) plt.axis('off') plt.savefig('after_process.jpg') i=2019030501#时间 for region in measure.regionprops(label_image): #循环得到每一个连通区域属性集 #忽略小区域 if region.area < 100: continue print(region.bbox) #绘制外包矩形 minr, minc, maxr, maxc = region.bbox rect = mpatches.Rectangle((minc-10, minr-10), maxc - minc+20, maxr - minr+20, fill=False, edgecolor='red', linewidth=2)# mpatches.Rectangle(矩形左上顶点坐标(x,y), width, height) print(rect) ax1.add_patch(rect) img=Image.open('1551254703(1).jpg') #矩形框坐标 left=minc-10 upper=minr-10 right=maxc+10 lower=maxr+10 print(left, upper, right, lower) cropped = img.crop((left, upper, right, lower))# cropped.save("cropped/%d.png"%i) i+=1 fig.tight_layout() plt.show()