用pyplot处理图像确实很简单,就是有点慢。
1.用imshow 显示图
2. 在二维坐标显示图
3.房子在 时空隧道扭曲了(3D坐标显示)
用核函数,在3D空间作图
4.是与外太空相连的虫洞入口
越中心旋转越大,靠近1旋转越小
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator
from skimage import data
import matplotlib.pyplot as plt
import numpy as np
class ZxpImage:
def __init__(self, img):
self.img = img
self.row, self.col, self.channel = img.shape
self.midy=self.col/2
self.midx=self.row/2
def luoxuan(self):
img2=self.img.copy()
for y in range(self.row) :
for x in range(self.col) :
tt=self.img[y,x]
yc=1.0*(y-self.midy)/self.midy
xc=1.0*(x-self.midx)/self.midx
r=np.sqrt(yc*yc+xc*xc)
s=(1-r)*(1-r);
if r < 1 : # 越中心旋转越大,靠近1旋转越小
ox=np.cos(s)*xc-np.sin(s)*yc
oy=np.sin(s)*xc+np.cos(s)*yc
dx=int(np.round(ox*self.midx+self.midx))
dy=int(np.round(oy*self.midy+self.midy))
dy= dy if dy<self.col else self.col-1
dx= dx if dx<self.row else self.row-1
img2[dy,dx]=tt
return img2
def colorvalue(self,tv ):
tt=tv/256.0
return tt;
def touyin2D(self,ax):
img2=self.img.copy()
myy=np.arange(self.row*self.col)
myx=np.arange(self.row*self.col)
colors=[]
i=0
for y in range(self.row) :
for x in range(self.col) :
tt=self.img[y,x]
yc=-1.0*(y-self.midy)+self.midy #为了把图像变正
xc=1.0*(x-self.midx) #以y轴为中心线
myy[i]=yc
myx[i]= xc
tc=self.colorvalue(tt)
colors.append(tc) #colors中放的每个像素的颜色值
i+=1
erea=1.0;
ax.scatter(myx,myy,s=erea, c=colors,alpha=1.0 ) #通过scatter逐点画图
return
def phi(self,v):
return v[0]*v[0], np.sqrt(2.0)*v[0]*v[1],v[1]*v[1]
def touyin3D(self,ax):
img2=self.img.copy()
myy=np.arange(self.row*self.col)
myx=np.arange(self.row*self.col)
myz=np.arange(self.row*self.col)
sqrt2=np.sqrt(2.0)
colors=[]
i=0
ory=self.row-85.0
for y in range(self.row) :
for x in range(self.col) :
tt=self.img[y,x]
yc=-1.0*(y-ory)
xc=1.0*(x-self.midx)
myy[i]= yc*yc
myx[i]=xc*xc
myz[i]=sqrt2*yc*xc
tc=self.colorvalue(tt)
colors.append(tc)
i+=1
erea=1;
ax.scatter(myx,myy,myz,s=erea, c=colors,alpha=1.0 )
ax.view_init(180, 35)
return
def main():
img=data.load('siheyuan.png')
#img=data.astronaut()
fig=plt.figure(num='siheyuan',figsize=(8,8))
ax1=fig.add_subplot(221) #将窗口分为两行两列四个子图,则可显示四幅图片
ax1.imshow(img) #显示原图
#plt.axis('off')
zxp=ZxpImage(img)
ax2=fig.add_subplot(222) #第二个子图
ax2.set_title('touyin2d')
zxp.touyin2D(ax2) #在二维坐标显示原图
#plt.imshow(img[:,:,0],plt.cm.gray)
#plt.axis('off') #不显示坐标尺寸
ax3=fig.add_subplot(223,projection='3d') #第三个子图
ax3.set_title('touyin3d' ) #在3维坐标显示变形图
zxp.touyin3D(ax3)
img2= zxp.luoxuan()
ax4=fig.add_subplot(224) #第四个子图
ax4.imshow(img2) #显示 图形变形后的图
#plt.axis('off') #不显示坐标尺寸
plt.show()
main()
越中心旋转越大,靠近1旋转越小
ox=np.cos(s)*xc-np.sin(s)*yc
oy=np.sin(s)*xc+np.cos(s)*yc
dx=int(np.round(ox*self.midx+self.midx))
dy=int(np.round(oy*self.midy+self.midy))
dy= dy if dy<self.col else self.col-1
dx= dx if dx<self.row else self.row-1
img2[dy,dx]=tt
return img2
def colorvalue(self,tv ):
tt=tv/256.0
return tt;
def touyin2D(self,ax):
img2=self.img.copy()
myy=np.arange(self.row*self.col)
myx=np.arange(self.row*self.col)
colors=[]
i=0
for y in range(self.row) :
for x in range(self.col) :
tt=self.img[y,x]
yc=-1.0*(y-self.midy)+self.midy #为了把图像变正
xc=1.0*(x-self.midx) #以y轴为中心线
myy[i]=yc
myx[i]= xc
tc=self.colorvalue(tt)
colors.append(tc) #colors中放的每个像素的颜色值
i+=1
erea=1.0;
ax.scatter(myx,myy,s=erea, c=colors,alpha=1.0 ) #通过scatter逐点画图
return
def phi(self,v):
return v[0]*v[0], np.sqrt(2.0)*v[0]*v[1],v[1]*v[1]
def touyin3D(self,ax):
img2=self.img.copy()
myy=np.arange(self.row*self.col)
myx=np.arange(self.row*self.col)
myz=np.arange(self.row*self.col)
sqrt2=np.sqrt(2.0)
colors=[]
i=0
ory=self.row-85.0
for y in range(self.row) :
for x in range(self.col) :
tt=self.img[y,x]
yc=-1.0*(y-ory)
xc=1.0*(x-self.midx)
myy[i]= yc*yc
myx[i]=xc*xc
myz[i]=sqrt2*yc*xc
tc=self.colorvalue(tt)
colors.append(tc)
i+=1
erea=1;
ax.scatter(myx,myy,myz,s=erea, c=colors,alpha=1.0 )
ax.view_init(180, 35)
return
def main():
img=data.load('siheyuan.png')
#img=data.astronaut()
fig=plt.figure(num='siheyuan',figsize=(8,8))
ax1=fig.add_subplot(221) #将窗口分为两行两列四个子图,则可显示四幅图片
ax1.imshow(img) #显示原图
#plt.axis('off')
zxp=ZxpImage(img)
ax2=fig.add_subplot(222) #第二个子图
ax2.set_title('touyin2d')
zxp.touyin2D(ax2) #在二维坐标显示原图
#plt.imshow(img[:,:,0],plt.cm.gray)
#plt.axis('off') #不显示坐标尺寸
ax3=fig.add_subplot(223,projection='3d') #第三个子图
ax3.set_title('touyin3d' ) #在3维坐标显示变形图
zxp.touyin3D(ax3)
img2= zxp.luoxuan()
ax4=fig.add_subplot(224) #第四个子图
ax4.imshow(img2) #显示 图形变形后的图
#plt.axis('off') #不显示坐标尺寸
plt.show()
main()
图的效果
进一步用svm.SVC处理图像,进行分界
clf_poly = svm.SVC(kernel='poly', degree=ploygree).fit(x, y)
当ploygree=2,ploygree=3 的超平面分解线(图2中的点为支持向量的点),可以如下图
上图调整了图3的显示角度
ploydegree=3
svc代码:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator
from skimage import data
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from sklearn import svm
class ZxpImage:
def __init__(self, img):
self.img = img
self.row, self.col, self.channel = img.shape
self.midy=self.col/2
self.midx=self.row/2
def luoxuan(self):
img2=self.img.copy()
for y in range(self.row) :
for x in range(self.col) :
tt=self.img[y,x]
yc=1.0*(y-self.midy)/self.midy
xc=1.0*(x-self.midx)/self.midx
r=np.sqrt(yc*yc+xc*xc)
s=(1-r)*(1-r);
if r < 1 :
ox=np.cos(s)*xc-np.sin(s)*yc
oy=np.sin(s)*xc+np.cos(s)*yc
dx=int(np.round(ox*self.midx+self.midx))
dy=int(np.round(oy*self.midy+self.midy))
if dy>=self.col :
contine
if dx>=self.row :
contine
img2[dy,dx]=tt
return img2
def colorvalue(self,tv ):
tt=tv/256.0
return tt;
def touyin2D(self,ax):
img2=self.img.copy()
myy=np.arange(self.row*self.col)
myx=np.arange(self.row*self.col)
colors=[]
i=0
for y in range(self.row) :
for x in range(self.col) :
tt=self.img[y,x]
#yc=-1.0*(y-self.midy)+self.midy
yc=y
xc=1.0*(x-self.midx)
myy[i]=yc
myx[i]= xc
tc=self.colorvalue(tt)
colors.append(tc)
i+=1
erea=1.0;
#myy=np.array(list(map(lambda tt: self.col-tt ,myy)))
ax.scatter(myx,myy,s=erea, c=colors,alpha=1.0 )
return
def fk(self,xm,support_,coef0,support_vectors_,dual_coef_,intercept_):
xn=support_vectors_
k1=[xn[i].dot(xm) for i in range(len(xn))]
k2=np.array([np.power(k1[i]+coef0,2) for i in range(len(k1)) ])
coef=dual_coef_[0]
co=np.array([coef[i] for i in range(len(coef)) ])
res=co.dot(k2)+ intercept_[0]
return res
def Paint2DLine(self,ax):
data = [[48,44],[70,74],[238,44],[216,74],[144,80],
[9,44],[30,74],[277,44],[256,74],[144,145]]
labels = [-1,-1,-1,-1,-1 ,1,1,1,1,1]
data=list(map(lambda tt:[tt[0]-self.midy,tt[1]],data))
x = np.array(data)
labels = np.array(labels)
y = np.array(labels)
dy=np.array([0.1,0.1,0])
dx= np.array(list([(x[i]+x[5+i ])/2 for i in [2,3,4]]))
ploygree=2
h=4
#x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.0)
x_test=x_train=x
y_test=y_train=y
x_min, x_max =-1*self.midy,self.midy
y_min, y_max =0,self.row
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
clf_poly = svm.SVC(kernel='poly', degree=ploygree,gamma=1.0,tol=0.00000001).fit(x, y)
clfr_poly = svm.SVR(kernel='poly', degree=ploygree,gamma=1.0,tol=0.00000001).fit(dx, dy)
clf=clf_poly
#answer = clf.predict(np.c_[xx.ravel(), yy.ravel()])
answer = clf_poly.predict(np.c_[xx.ravel(), yy.ravel()])
answer1 = clfr_poly.predict(np.c_[xx.ravel(), yy.ravel()])
print(clf)
print("coef={},{}".format(clf._dual_coef_, clf._intercept_))
print(clfr_poly)
print("coef1={},{}".format(clfr_poly._dual_coef_, clfr_poly._intercept_))
xt=x[0]
mmxx=clf.predict([xt])
print("mmxx0="+str(mmxx))
mmxx=self.fk(xt,clf.support_,clf.coef0,clf.support_vectors_, clf._dual_coef_, clf._intercept_)
print("mmxx{}={}".format(xt, mmxx))
#print(np.mean( answer == y_train))
z = answer.reshape(xx.shape)
z1 = answer1.reshape(xx.shape)
#yy=np.array(list(map(lambda tt: self.col-tt ,yy)))
ax.contourf(xx, yy, z, cmap=plt.cm.Paired, alpha=0.3)
C = ax.contour(xx, yy, z,[0], colors = 'yellow',linewidth=1)
#ax.contour(xx, yy, z1,[-1,0,1], colors = 'red',linewidth=1)
# 绘制等高线数据
ax.clabel(C, inline = False, fontsize = 8,colors='green',rightside_up=True)
# Plot also the training points
#x_train=np.array(list(map(lambda tt: [tt[0],self.col-tt[1]] ,x_train)))
ax.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.cm.Paired)
def phi(self,v):
return v[0]*v[0], np.sqrt(2.0)*v[0]*v[1],v[1]*v[1]
def touyin3D(self,ax):
img2=self.img.copy()
myy=np.arange(self.row*self.col)
myx=np.arange(self.row*self.col)
myz=np.arange(self.row*self.col)
sqrt2=np.sqrt(2.0)
colors=[]
i=0
ory=self.row-80.0
for y in range(self.row) :
for x in range(self.col) :
tt=self.img[y,x]
yc=-1.0*(y-ory)
xc=1.0*(x-self.midx)
myy[i]= yc*yc
myx[i]=-xc*xc
myz[i]=sqrt2*yc*xc
tc=self.colorvalue(tt)
colors.append(tc)
i+=1
erea=1;
ax.scatter(myy,myz,myx,s=erea, c=colors,alpha=1.0 )
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
#ax.invert_zaxis()
ax.view_init(-45, 0)
#ax.view_init(0, 45)
return
def main():
img=data.load('siheyuan.png')
#img=data.astronaut()
fig=plt.figure(num='siheyuan',figsize=(8,8))
ax1=fig.add_subplot(221) #将窗口分为两行两列四个子图,则可显示四幅图片
ax1.imshow(img) #显示原图
#plt.axis('off')
zxp=ZxpImage(img)
ax2=fig.add_subplot(222) #第二个子图
ax2.set_title('touyin2d')
zxp.touyin2D(ax2) #在二维坐标显示原图
zxp.Paint2DLine(ax2)
ax2.invert_yaxis()
#plt.imshow(img[:,:,0],plt.cm.gray)
#plt.axis('off') #不显示坐标尺寸
ax3=fig.add_subplot(223,projection='3d') #第三个子图
ax3.set_title('touyin3d' ) #在3维坐标显示变形图
zxp.touyin3D(ax3)
img2= zxp.luoxuan()
ax4=fig.add_subplot(224) #第四个子图
ax4.imshow(img2) #显示 图形变形后的图
#plt.axis('off') #不显示坐标尺寸
plt.show()
main()