背景
我的程序所做的是导入二值化图像并将图像中的每个白色像素映射到 x-y 平面。我对这部分代码没有任何问题,但是当我告诉程序以 14 的间隔绘制每个像素时,它给出的图不是等距的。例如,如果我有一组 x 点 [x_1 x_2 x_3 x_4 x_5....x_n] 和 y 点 [y_1 y_2 y_3 y_4 y_5....y_n] 并且我想在 2 的间隔内绘制像素,它将有一个如下所示的列表: [x_1 x_3 x_5....x_n] 和 [y_1 y_3 y_5....y_n]。
代码
import numpy as np
import tkinter
import matplotlib
import matplotlib.pyplot as plt
import time
matplotlib.use('TkAgg')
from vpython import *
from numpy import loadtxt
import math
from PIL import Image
import os
import cv2
from pylab import plot, ginput, show, axis
import matplotlib.image as mpimg
from statistics import mean
im = cv2.imread('/Users/beadpile/Desktop/aman/geeks12.jpg')
blue = [255,255,255]
black = [0,0,0]
# Get X and Y coordinates of all blue pixels
Y, X = np.where(np.all(im==blue,axis=2))
print(max(X))
xpoints = np.array(X)
ypoints = -np.array(Y)
test_list=list(zip(xpoints, ypoints))
points = dict()
f = plt.figure()
f.set_figwidth(30)
f.set_figheight(2)
#To find the max points of white region to plot the edges instead of the whole region
for x,y in test_list:
if x not in points or points[x]<y:
points[x]=y
x,y = zip(*points.items())
# I start to define interval here
xdif=[]
ydif=[]
print("len",len(xpoints))
for j in range(0,len(x),14):
d=x[j]
xdif.append(d)
for i in range(0,len(x),14):
e=y[i]
ydif.append(e)
print(ypoints, xpoints)
plt.plot(xdif, ydif, '*',markersize=6, color='red')
#plt.plot(xx, yy, '*',markersize=2, color='red')
plt.plot(x, y,".", markersize=2,color='blue')
plt.show()
问题
当您绘制点时,它会给出不规则放置的点;在某些区域中,两个连续像素比我定义的间隔更近,而有些则更远。 例如,这是我得到的情节
星星是区间内的点。但似乎在 100 到 200 之间,连续像素更接近,而其他地方则更远。如果我从列表中每隔 14 个位置选取一个像素,那么我应该得到一个与其相似的图,但事实并非如此。例如,如果我有一组点并且想要绘制 x 轴的每个第二个位置,我应该得到这样的结果 我该如何解决这个问题并绘制像素?
您假设蓝色像素坐标 (
X
和 Y
) 首先沿 x 轴等距排列并排序,最终产生沿 x 轴等距排列的子样本。但是,numpy.where
首先返回沿 y 轴排序的非零条目。
In [5]: a = np.zeros((3, 2), dtype=bool)
In [6]: a[1, 1] = True
In [7]: a[2, 0] = True
In [8]: a
Out[8]:
array([[False, False],
[False, True],
[ True, False]])
In [9]: np.where(a)
Out[9]: (array([1, 2]), array([1, 0]))
由于您没有提供示例图像,因此很难测试解决方案。但是,用代码中的相应赋值替换以下行应该可以解决这个特定问题(可能还有其他问题):
X, Y = np.where(np.all(im==blue,axis=2).T)