python - 检测4个有趣的像素

标签 python image python-2.7 opencv pixels

我使用OpenCV读取了这张图片:

我检测其中的对象边界并显示图片:

这是我的代码:

import cv2
import numpy as np
from matplotlib import pyplot as plt


im=cv2.imread('db/4.jpg')
#mask=np.zeros(img.shape[:2],np.uint8)
imgray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh=cv2.threshold(imgray,242,245,235)
contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

cv2.drawContours(im,contours,-1,(0,255,0),3)
cv2.imshow("GL",im)
cv2.waitKey(0)
cv2.destroyAllWindows()

我想做的事:

我想拥有属于轮廓之一的4个像素的坐标,并且:
  • 第一个是X轴的壁橱
  • 第二个距离X轴最远
  • 第三个是Y轴壁橱
  • 第四个离Y轴最远的位置

  • 请注意,我的代码中轮廓变量的数量可能会因阅读的图片而异。

    最佳答案

    您可以将所有轮廓堆叠到一个数组green中,并搜索最小/最大x / y值:

    green = np.vstack(contours).reshape((-1, 2))
    print "Min X:", green[np.where(green[:, 0] == green[:, 0].min()), :]
    print "Man X:", green[np.where(green[:, 0] == green[:, 0].max()), :]
    print "Min Y:", green[np.where(green[:, 1] == green[:, 1].min()), :]
    print "Man Y:", green[np.where(green[:, 1] == green[:, 1].max()), :]
    

    请注意,尤其是对于矩形,有多个像素可以满足您的要求,因为它们与x或y轴的距离相等。

    这是“四个”像素的可视化:

    生成的PyLab代码:
    pl.imshow(im)
    pl.gca().autoscale(False)
    minX = np.where(green[:, 0] == green[:, 0].min())
    maxX = np.where(green[:, 0] == green[:, 0].max())
    minY = np.where(green[:, 1] == green[:, 1].min())
    maxY = np.where(green[:, 1] == green[:, 1].max())
    pl.plot(green[minX, 0], green[minX, 1], 'ro')
    pl.plot(green[maxX, 0], green[maxX, 1], 'go')
    pl.plot(green[minY, 0], green[minY, 1], 'bo')
    pl.plot(green[maxY, 0], green[maxY, 1], 'yo')
    

    关于python - 检测4个有趣的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28704766/

    相关文章:

    python - 获取图像的焦点像素

    Python groupby 结果计数频率

    Java 将来自 URL 的图像添加到我的 JPanel

    c# - Bitmap Region is already locked 异常

    python - 如何将 ResultProxy 更改为字符串

    python - 通过 XML 解析时保留 CDATA 部分

    python - MONGO_QUERY_BLACKLIST 不起作用

    html - 创建半透明图像叠加层

    Python:EOFError:读取一行时为EOF

    python - Tkinter 网格管理器(类型错误)