示例#1
0
def change_photo_size(photo, new_photo, x_size, y_size):

    if os.path.lexists(photo):
        if os.path.getsize(photo) > 0:

            foto_orig = Image.open(photo)
            foto_mod = foto_orig.resize((x_size, y_size))
            foto_mod.save(new_photo, quality=90)

            im = pyopencv.imread(new_photo)

            if pyopencv.imwrite(new_photo + '_new', im):
                os.remove(new_photo)
                os.rename(new_photo + '_new', new_photo)

            if os.path.lexists(new_photo):

                os.remove(photo)

            else:

                print 'Nao foi possivel modificar a foto.'

        else:
            print 'A foto esta vazia.'
    else:
        print 'A foto nao foi achada.'
 def __init__(self, *args, **kwargs):
     super(MorphologyDemo, self).__init__(*args, **kwargs)
     self.structing_element = np.ones((3, 3), dtype=np.uint8)
     self.img = cv.imread("lena.jpg")
     self.on_trait_change(self.redraw,
                          "structing_element,process_type,iter")
     self.redraw()
    def __init__(self, **traits):
        super(HistDemo, self).__init__(**traits)
        img = cv.imread("lena.jpg")
        gray_img = cv.Mat()
        cv.cvtColor(img, gray_img, cv.CV_BGR2GRAY)
        self.img = gray_img
        self.img2 = self.img.clone()
        result = cv.MatND()

        r = cv.vector_float32([0, 256])
        ranges = cv.vector_vector_float32([r, r])

        cv.calcHist(
            cv.vector_Mat([self.img]),
            channels=cv.vector_int([0, 1]),
            mask=cv.Mat(),
            hist=result,
            histSize=cv.vector_int([256]),
            ranges=ranges,
        )

        data = ArrayPlotData(x=np.arange(0, len(result[:])), y=result[:])
        self.plot = Plot(data, padding=10)
        line = self.plot.plot(("x", "y"))[0]
        self.select_tool = RangeSelection(line, left_button_selects=True)
        line.tools.append(self.select_tool)
        self.select_tool.on_trait_change(self._selection_changed, "selection")
        line.overlays.append(RangeSelectionOverlay(component=line))

        cv.imshow("Hist Demo", self.img)

        self.timer = Timer(50, self.on_timer)
 def __init__(self, **traits):
     super(AffineDemo, self).__init__(**traits)
     self.img = cv.imread("lena.jpg")
     self.m = np.array([[0.5, -0.3, 100], [0.3, 0.5, 0]])
     size = self.img.size()
     self.on_trait_change(self.redraw, "m,size")
     self.size = np.array([[size.width, size.height]])
def load_image(path, swap=False):
    '''
    '''
    frame = cv.imread(path, 1)
    if swap:
        cv.convertImage(frame, frame, cv.CV_CVTIMG_SWAP_RB)
    return frame
 def __init__(self, **traits):
     super(AffineDemo, self).__init__(**traits)
     self.img = cv.imread("lena.jpg")
     self.m = np.array([[0.5,-0.3,100],[0.3,0.5,0]])
     size = self.img.size()
     self.on_trait_change(self.redraw, "m,size")
     self.size = np.array([[size.width, size.height]])
示例#7
0
    def __init__(self, **traits):
        super(HistDemo, self).__init__(**traits)
        img = cv.imread("lena.jpg")
        gray_img = cv.Mat()
        cv.cvtColor(img, gray_img, cv.CV_BGR2GRAY)
        self.img = gray_img
        self.img2 = self.img.clone()
        result = cv.MatND()

        r = cv.vector_float32([0, 256])
        ranges = cv.vector_vector_float32([r, r])

        cv.calcHist(cv.vector_Mat([self.img]),
                    channels=cv.vector_int([0, 1]),
                    mask=cv.Mat(),
                    hist=result,
                    histSize=cv.vector_int([256]),
                    ranges=ranges)

        data = ArrayPlotData(x=np.arange(0, len(result[:])), y=result[:])
        self.plot = Plot(data, padding=10)
        line = self.plot.plot(("x", "y"))[0]
        self.select_tool = RangeSelection(line, left_button_selects=True)
        line.tools.append(self.select_tool)
        self.select_tool.on_trait_change(self._selection_changed, "selection")
        line.overlays.append(RangeSelectionOverlay(component=line))

        cv.imshow("Hist Demo", self.img)

        self.timer = Timer(50, self.on_timer)
 def __init__(self, **traits):
     super(PerspectiveDemo, self).__init__(**traits)
     self.img = cv.imread("lena.jpg")
     w = self.img.size().width
     h = self.img.size().height
     self.src = np.array([[0,0],[w,0],[0,h],[w,h]],dtype=np.float32)
     self.dst = np.array([[0,0],[w,0],[0,h],[w,h]],dtype=np.float32)
     self.on_trait_change(self.redraw, "src,dst")
     self.redraw()
示例#9
0
 def __init__(self, **traits):
     super(PerspectiveDemo, self).__init__(**traits)
     self.img = cv.imread("lena.jpg")
     w = self.img.size().width
     h = self.img.size().height
     self.src = np.array([[0, 0], [w, 0], [0, h], [w, h]], dtype=np.float32)
     self.dst = np.array([[0, 0], [w, 0], [0, h], [w, h]], dtype=np.float32)
     self.on_trait_change(self.redraw, "src,dst")
     self.redraw()
 def __init__(self, *args, **kwargs):
     super(RemapDemo, self).__init__(*args, **kwargs)
     self.img = cv.imread("lena.jpg")
     self.size = self.img.size()
     self.w, self.h = self.size.width, self.size.height
     self.dstimg = cv.Mat()
     self.map1 = cv.Mat(self.size, cv.CV_32FC1)
     self.map2 = cv.Mat(self.size, cv.CV_32FC1)
     self.gridimg = self.make_grid_img()
     self.on_trait_change(self.redraw, "surf_func,range,view_height,grid")
示例#11
0
 def __init__(self, *args, **kwargs):
     super(RemapDemo, self).__init__(*args, **kwargs)
     self.img = cv.imread("lena.jpg")
     self.size = self.img.size()
     self.w, self.h = self.size.width, self.size.height
     self.dstimg = cv.Mat()
     self.map1 = cv.Mat(self.size, cv.CV_32FC1)
     self.map2 = cv.Mat(self.size, cv.CV_32FC1)
     self.gridimg = self.make_grid_img()
     self.on_trait_change(self.redraw, "surf_func,range,view_height,grid")
 def __init__(self, *args, **kwargs):
     super(SURFDemo, self).__init__(*args, **kwargs)
     img = cv.imread("lena_small.jpg")
     self.m = np.array([[0.8,-0.6,60],[0.6,0.7,-20]])
     self.img1 = cv.Mat()
     cv.cvtColor(img, self.img1, cv.CV_BGR2GRAY)       
     self.affine()
     self.on_trait_change(self.redraw, "max_distance,draw_circle")
     self.on_trait_change(self.recalculate, "m,hessian_th,octaves,layers")
     self.recalculate()
     self.redraw()
示例#13
0
 def __init__(self, *args, **kwargs):
     super(SURFDemo, self).__init__(*args, **kwargs)
     img = cv.imread("lena_small.jpg")
     self.m = np.array([[0.8, -0.6, 60], [0.6, 0.7, -20]])
     self.img1 = cv.Mat()
     cv.cvtColor(img, self.img1, cv.CV_BGR2GRAY)
     self.affine()
     self.on_trait_change(self.redraw, "max_distance,draw_circle")
     self.on_trait_change(self.recalculate, "m,hessian_th,octaves,layers")
     self.recalculate()
     self.redraw()
 def __init__(self, *args, **kwargs):
     super(HoughDemo, self).__init__(*args, **kwargs)
     
     self.img = cv.imread("stuff.jpg")
     self.img_gray = cv.Mat()
     cv.cvtColor(self.img, self.img_gray, cv.CV_BGR2GRAY)
     
     self.img_smooth = self.img_gray.clone()
     cv.smooth(self.img_gray, self.img_smooth, cv.CV_GAUSSIAN, 7, 7, 0, 0)
     
     self.redraw()
     
     self.on_trait_change(self.redraw,
         "th1,th2,show_canny,rho,theta,hough_th,minlen,maxgap,dp,mindist,param1,param2")
 def __init__(self, *args, **kwargs):
     super(InPaintDemo, self).__init__(*args, **kwargs)
     self.img = cv.imread("stuff.jpg") # 原始图像
     self.img2 = self.img.clone() # inpaint效果预览图像
     self.mask = cv.Mat(self.img.size(), cv.CV_8UC1) # 储存选区的图像
     self.mask[:] = 0
     self.data = ArrayPlotData(img = self.img[:,:,::-1])
     self.plot = Plot(self.data, padding=10, 
         aspect_ratio=float(self.img.size().width)/self.img.size().height)
     self.plot.x_axis.visible = False
     self.plot.y_axis.visible = False
     imgplot = self.plot.img_plot("img", origin="top left")[0]
     self.painter = CirclePainter(component=imgplot)
     imgplot.overlays.append(self.painter)
 def __init__(self, *args, **kwargs):
     self.lo_diff.fill(5)
     self.hi_diff.fill(5)
     self.img = cv.imread("lena.jpg")
     self.data = ArrayPlotData(img = self.img[:,:,::-1])
     w = self.img.size().width
     h = self.img.size().height
     self.plot = Plot(self.data, padding=10, aspect_ratio=float(w)/h)
     self.plot.x_axis.visible = False
     self.plot.y_axis.visible = False
     self.imgplot = self.plot.img_plot("img", origin="top left")[0]
     self.imgplot.interpolation = "nearest"
     self.imgplot.overlays.append(PointPicker(application=self, component=self.imgplot))
     
     self.on_trait_change(self.redraw, "point,lo_diff,hi_diff,option")
示例#17
0
    def __init__(self, *args, **kwargs):
        self.lo_diff.fill(5)
        self.hi_diff.fill(5)
        self.img = cv.imread("lena.jpg")
        self.data = ArrayPlotData(img=self.img[:, :, ::-1])
        w = self.img.size().width
        h = self.img.size().height
        self.plot = Plot(self.data, padding=10, aspect_ratio=float(w) / h)
        self.plot.x_axis.visible = False
        self.plot.y_axis.visible = False
        self.imgplot = self.plot.img_plot("img", origin="top left")[0]
        self.imgplot.interpolation = "nearest"
        self.imgplot.overlays.append(
            PointPicker(application=self, component=self.imgplot))

        self.on_trait_change(self.redraw, "point,lo_diff,hi_diff,option")
示例#18
0
 def __init__(self, *args, **kwargs):
     super(InPaintDemo, self).__init__(*args, **kwargs)
     self.img = cv.imread("stuff.jpg")  # 原始图像
     self.img2 = self.img.clone()  # inpaint效果预览图像
     self.mask = cv.Mat(self.img.size(), cv.CV_8UC1)  # 储存选区的图像
     self.mask[:] = 0
     self.data = ArrayPlotData(img=self.img[:, :, ::-1])
     self.plot = Plot(self.data,
                      padding=10,
                      aspect_ratio=float(self.img.size().width) /
                      self.img.size().height)
     self.plot.x_axis.visible = False
     self.plot.y_axis.visible = False
     imgplot = self.plot.img_plot("img", origin="top left")[0]
     self.painter = CirclePainter(component=imgplot)
     imgplot.overlays.append(self.painter)
    def __init__(self):
        #读入图像
        img = cv.imread("lena_full.jpg")
        img2 = cv.Mat()
        cv.cvtColor(img, img2, cv.CV_BGR2GRAY)
        img = cv.Mat()
        cv.resize(img2, img, cv.Size(N, N))
        self.fimg = fft.fft2(img[:])  # 图像的频域信号
        mag_img = np.log10(np.abs(self.fimg))

        # 创建计算用图像
        filtered_img = np.zeros((N, N), dtype=np.float)
        self.mask = np.zeros((N, N), dtype=np.float)
        self.mask_img = cv.asMat(self.mask)  # 在self.mask上绘制多边形用的图像

        # 创建数据源
        self.data = ArrayPlotData(mag_img=fft.fftshift(mag_img),
                                  filtered_img=filtered_img,
                                  mask_img=self.mask)

        # 创建三个图像绘制框以及容器
        meg_plot, img = self.make_image_plot("mag_img")
        mask_plot, _ = self.make_image_plot("mask_img")
        filtered_plot, _ = self.make_image_plot("filtered_img")
        self.plot = HPlotContainer(meg_plot, mask_plot, filtered_plot)

        # 创建套索工具
        lasso_selection = LassoSelection(component=img)
        lasso_overlay = LassoOverlay(lasso_selection=lasso_selection,
                                     component=img,
                                     selection_alpha=0.3)
        img.tools.append(lasso_selection)
        img.overlays.append(lasso_overlay)
        self.lasso_selection = lasso_selection

        # 监听套索工具的事件、开启时钟事件
        lasso_selection.on_trait_change(self.lasso_updated,
                                        "disjoint_selections")
        self.timer = Timer(50, self.on_timer)
 def __init__(self):
     #读入图像
     img = cv.imread("lena_full.jpg")
     img2 = cv.Mat()
     cv.cvtColor(img, img2, cv.CV_BGR2GRAY)
     img = cv.Mat()
     cv.resize(img2, img, cv.Size(N, N))
     self.fimg = fft.fft2(img[:]) # 图像的频域信号
     mag_img = np.log10(np.abs(self.fimg))
 
     # 创建计算用图像
     filtered_img = np.zeros((N, N), dtype=np.float)
     self.mask = np.zeros((N, N), dtype=np.float)
     self.mask_img = cv.asMat(self.mask) # 在self.mask上绘制多边形用的图像
     
     # 创建数据源
     self.data = ArrayPlotData(
         mag_img = fft.fftshift(mag_img),
         filtered_img = filtered_img,
         mask_img = self.mask
     )
     
     # 创建三个图像绘制框以及容器
     meg_plot, img = self.make_image_plot("mag_img")
     mask_plot, _ = self.make_image_plot("mask_img")       
     filtered_plot, _ = self.make_image_plot("filtered_img")
     self.plot = HPlotContainer(meg_plot, mask_plot, filtered_plot)     
     
     # 创建套索工具
     lasso_selection = LassoSelection(component=img)
     lasso_overlay = LassoOverlay(lasso_selection = lasso_selection, component=img, selection_alpha=0.3)
     img.tools.append(lasso_selection)
     img.overlays.append(lasso_overlay)
     self.lasso_selection = lasso_selection                 
     
     # 监听套索工具的事件、开启时钟事件
     lasso_selection.on_trait_change(self.lasso_updated, "disjoint_selections")
     self.timer = Timer(50, self.on_timer)
# -*- coding: utf-8 -*-

import pyopencv as cv
import numpy as np

img = cv.imread("fruits_section.jpg") 
img_hsv = cv.Mat()
cv.cvtColor(img, img_hsv, cv.CV_BGR2HSV) 

channels = cv.vector_int([0, 1])
result = cv.MatND()

r = cv.vector_float32([0, 256])
ranges = cv.vector_vector_float32([r, r])

cv.calcHist(cv.vector_Mat([img_hsv]), channels, cv.Mat(),  
            result, cv.vector_int([40, 40]), ranges) 

result[:] /= np.max(result[:]) / 255 
2###
img2 = cv.imread("fruits.jpg") 
img_hsv2 = cv.Mat()
cv.cvtColor(img2, img_hsv2, cv.CV_BGR2HSV)

img_bp = cv.Mat()
cv.calcBackProject(cv.vector_Mat([img_hsv2]), 
                   channels=channels, 
                   hist=result, 
                   backProject=img_bp, 
                   ranges = ranges) 
3###
示例#22
0
    cv.namedWindow("Object Correspond", 1)

    colors = [
        cv.Scalar(0, 0, 255),
        cv.Scalar(0, 128, 255),
        cv.Scalar(0, 255, 255),
        cv.Scalar(0, 255, 0),
        cv.Scalar(255, 128, 0),
        cv.Scalar(255, 255, 0),
        cv.Scalar(255, 0, 0),
        cv.Scalar(255, 0, 255),
        cv.Scalar(255, 255, 255),
    ]

    # read the two images
    object_color = cv.imread(object_filename, cv.CV_LOAD_IMAGE_COLOR)
    image = cv.imread(scene_filename, cv.CV_LOAD_IMAGE_GRAYSCALE)
    if not object_color or not image:
        print("Can not load %s and/or %s\n" \
            "Usage: find_obj [<object_filename> <scene_filename>]\n" \
            % (object_filename, scene_filename))
        exit(-1)
    object = cv.Mat(object_color.size(), cv.CV_8UC1)
    cv.cvtColor(object_color, object, cv.CV_BGR2GRAY)

    # corners
    src_corners = [
        cv.Point(0, 0),
        cv.Point(object.cols, 0),
        cv.Point(object.cols, object.rows),
        cv.Point(0, object.rows)
 def __init__(self, *args, **kwargs):
     super(MeanShiftDemo, self).__init__(*args, **kwargs)
     self.img = cv.imread("fruits.jpg")
     self.img2 = self.img.clone()
     self.on_trait_change(self.redraw, "do_button")
     self.redraw()
示例#24
0
import numpy as np
import pyopencv as cv2

# Load an color image in grayscale
img = cv2.imread('IMG.jpeg', 0)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('1.png', img)
# -*- coding: utf-8 -*-
import numpy as np
from numpy import fft
import pyopencv as cv
import matplotlib.pyplot as plt


N = 256
img = cv.imread("lena_full.jpg")
img2 = cv.Mat()
cv.cvtColor(img, img2, cv.CV_BGR2GRAY)
img = cv.Mat()
cv.resize(img2, img, cv.Size(N, N))


fimg = fft.fft2(img[:])
mag_img = np.log10(np.abs(fimg))
shift_mag_img = fft.fftshift(mag_img)


rects = [(80,125,85,130),(90,90,95,95),
         (150, 10, 250, 250), (110, 110, 146, 146)]
         
filtered_results = []
for i, (x0, y0, x1, y1) in enumerate(rects):
    mask = np.zeros((N, N), dtype=np.bool) 
    mask[x0:x1+1, y0:y1+1] = True 
    mask[N-x1:N-x0+1, N-y1:N-y0+1] = True 
    mask = fft.fftshift(mask) 
    fimg2 = fimg * mask  
    filtered_img = fft.ifft2(fimg2).real 
示例#26
0
import numpy as np
import pyopencv as cv2

# Load an color image in grayscale
img = cv2.imread('IMG.jpeg',0)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('1.png', img)
示例#27
0
    cv.erode(image, dest, element)
    cv.imshow("Opening&Closing window",dest);
def Erosion(pos, user_data):
    element = cv.asMat(np.ones((pos*2+1, pos*2+1), 'uint8'), True)
    cv.erode(src, dest, element)
    cv.imshow("Erosion&Dilation window",dest);
def Dilation(pos, user_data):
    element = cv.asMat(np.ones((pos*2+1, pos*2+1), 'uint8'), True)
    cv.dilate(src, dest, element)
    cv.imshow("Erosion&Dilation window",dest);

if __name__ == "__main__":
    filename = "baboon.jpg"
    if len(sys.argv)==2:
        filename = sys.argv[1]
    src = cv.imread(filename,1)
    if src.empty():
        sys.exit(-1)
    image = src.clone()
    dest = src.clone()
    cv.namedWindow("Opening&Closing window",1)
    cv.namedWindow("Erosion&Dilation window",1)
    cv.imshow("Opening&Closing window",src)
    cv.imshow("Erosion&Dilation window",src)
    cv.createTrackbar("Open","Opening&Closing window",0,10,Opening)
    cv.createTrackbar("Close","Opening&Closing window",0,10,Closing)
    cv.createTrackbar("Dilate","Erosion&Dilation window",0,10,Dilation)
    cv.createTrackbar("Erode","Erosion&Dilation window",0,10,Erosion)
    cv.waitKey(0)
    
示例#28
0
 def __init__(self, *args, **kwargs):
     super(FilterDemo, self).__init__(*args, **kwargs)
     self.kernel = np.ones((3, 3))
     self.img = cv.imread("lena.jpg")
     self.on_trait_change(self.redraw, "kernel,scale")
     self.scale = 1.0 / 9.0
 def __init__(self, *args, **kwargs):
     super(FilterDemo, self).__init__(*args, **kwargs)
     self.kernel = np.ones((3,3))
     self.img = cv.imread("lena.jpg")
     self.on_trait_change(self.redraw, "kernel,scale")
     self.scale = 1.0 / 9.0
 def __init__(self, *args, **kwargs):
     super(MorphologyDemo, self).__init__(*args, **kwargs)
     self.structing_element = np.ones((3,3), dtype=np.uint8)
     self.img = cv.imread("lena.jpg")
     self.on_trait_change(self.redraw, "structing_element,process_type,iter")
     self.redraw()
# -*- coding: utf-8 -*-
import pyopencv as cv
import sys

try:
    filename = sys.argv[1]
except:
    filename = "lena.jpg"
img = cv.imread( filename )
cv.namedWindow("demo1")
cv.imshow("demo1", img)
cv.waitKey(0)
# -*- coding: utf-8 -*-
import pyopencv as cv
import matplotlib.pyplot as plt

img = cv.imread("fruits.jpg")

#srs = [20, 40, 80]
srs = [20]
for i, sr in enumerate(srs):
    img2 = img.clone()
    result = cv.pyrMeanShiftFiltering(img, img2, 20, sr, 1)
    plt.subplot(100+len(srs)*10+i+1)
    plt.imshow(img2[:,:,::-1])
    plt.gca().set_axis_off()
    
plt.subplots_adjust(0.02, 0, 0.98, 1, 0.02, 0)    
plt.show()
示例#33
0
def Erosion(pos, user_data):
    element = cv.asMat(np.ones((pos * 2 + 1, pos * 2 + 1), 'uint8'), True)
    cv.erode(src, dest, element)
    cv.imshow("Erosion&Dilation window", dest)


def Dilation(pos, user_data):
    element = cv.asMat(np.ones((pos * 2 + 1, pos * 2 + 1), 'uint8'), True)
    cv.dilate(src, dest, element)
    cv.imshow("Erosion&Dilation window", dest)


if __name__ == "__main__":
    filename = "baboon.jpg"
    if len(sys.argv) == 2:
        filename = sys.argv[1]
    src = cv.imread(filename, 1)
    if src.empty():
        sys.exit(-1)
    image = src.clone()
    dest = src.clone()
    cv.namedWindow("Opening&Closing window", 1)
    cv.namedWindow("Erosion&Dilation window", 1)
    cv.imshow("Opening&Closing window", src)
    cv.imshow("Erosion&Dilation window", src)
    cv.createTrackbar("Open", "Opening&Closing window", 0, 10, Opening)
    cv.createTrackbar("Close", "Opening&Closing window", 0, 10, Closing)
    cv.createTrackbar("Dilate", "Erosion&Dilation window", 0, 10, Dilation)
    cv.createTrackbar("Erode", "Erosion&Dilation window", 0, 10, Erosion)
    cv.waitKey(0)
示例#34
0
 def __init__(self, *args, **kwargs):
     super(MeanShiftDemo, self).__init__(*args, **kwargs)
     self.img = cv.imread("fruits.jpg")
     self.img2 = self.img.clone()
     self.on_trait_change(self.redraw, "do_button")
     self.redraw()
示例#35
0
    cv.namedWindow("Object Correspond", 1)

    colors = [
        cv.Scalar(0,0,255),
        cv.Scalar(0,128,255),
        cv.Scalar(0,255,255),
        cv.Scalar(0,255,0),
        cv.Scalar(255,128,0),
        cv.Scalar(255,255,0),
        cv.Scalar(255,0,0),
        cv.Scalar(255,0,255),
        cv.Scalar(255,255,255),
    ]

    # read the two images
    object_color = cv.imread( object_filename, cv.CV_LOAD_IMAGE_COLOR )
    image = cv.imread( scene_filename, cv.CV_LOAD_IMAGE_GRAYSCALE )
    if not object_color or not image:
        print("Can not load %s and/or %s\n" \
            "Usage: find_obj [<object_filename> <scene_filename>]\n" \
            % (object_filename, scene_filename))
        exit(-1)
    object = cv.Mat(object_color.size(), cv.CV_8UC1)
    cv.cvtColor( object_color, object, cv.CV_BGR2GRAY )
    
    # corners
    src_corners = [cv.Point(0,0), cv.Point(object.cols, 0), cv.Point(object.cols, object.rows), cv.Point(0, object.rows)]
    dst_corners = [cv.Point()]*4

    # find keypoints on both images
    surf = cv.SURF(500, 4, 2, True)
示例#36
0
# -*- coding: utf-8 -*-

import pyopencv as cv
import numpy as np

img = cv.imread("fruits_section.jpg")
img_hsv = cv.Mat()
cv.cvtColor(img, img_hsv, cv.CV_BGR2HSV)

channels = cv.vector_int([0, 1])
result = cv.MatND()

r = cv.vector_float32([0, 256])
ranges = cv.vector_vector_float32([r, r])

cv.calcHist(cv.vector_Mat([img_hsv]), channels, cv.Mat(), result,
            cv.vector_int([40, 40]), ranges)

result[:] /= np.max(result[:]) / 255
2  ###
img2 = cv.imread("fruits.jpg")
img_hsv2 = cv.Mat()
cv.cvtColor(img2, img_hsv2, cv.CV_BGR2HSV)

img_bp = cv.Mat()
cv.calcBackProject(cv.vector_Mat([img_hsv2]),
                   channels=channels,
                   hist=result,
                   backProject=img_bp,
                   ranges=ranges)
3  ###
示例#37
0
# -*- coding: utf-8 -*-
import pyopencv as cv
import matplotlib.pyplot as plt

img = cv.imread("fruits.jpg")
threshold2 = [10, 30, 60]
for i, th2 in enumerate(threshold2):
    img2 = img.clone()
    storage = cv.createMemStorage(0)
    result = cv.pyrSegmentation(img, img2, storage, 4, 200, th2)

    plt.subplot(100 + len(threshold2) * 10 + i + 1)
    plt.imshow(img2[:, :, ::-1])
    plt.gca().set_axis_off()

plt.subplots_adjust(0.02, 0, 0.98, 1, 0.02, 0)
plt.show()
示例#38
0
# -*- coding: utf-8 -*-
import pyopencv as cv
import sys

try:
    filename = sys.argv[1]
except:
    filename = "lena.jpg"
img = cv.imread(filename)
cv.namedWindow("demo1")
cv.imshow("demo1", img)
cv.waitKey(0)
# -*- coding: utf-8 -*-
import pyopencv as cv

img = cv.imread("lena.jpg")
img2 = cv.Mat(img.size(), cv.CV_8UC4)

w, h = img.size().width, img.size().height

def blend(img, img2): 
    """
    混合两幅图像, 其中img2有4个通道
    """
    #使用alpha通道计算img2的混和值
    b = img2[:,:,3:] / 255.0     
    a = 1 - b # img的混合值

    #混合两幅图像
    img[:,:,:3] *= a  
    img[:,:,:3] += b * img2[:,:,:3]

img2[:] = 0
for i in xrange(0, w, w/10): 
    cv.line(img2, cv.Point(i,0), cv.Point(i, h),  
        cv.Scalar(0, 0, 255, i*255/w), 5)

blend(img, img2) 

img2[:] = 0        
for i in xrange(0, h, h/10):
    cv.line(img2, cv.Point(0,i), cv.Point(w, i), 
        cv.Scalar(0, 255, 0, i*255/h), 5)
示例#40
0
# -*- coding: utf-8 -*-
import numpy as np
from numpy import fft
import pyopencv as cv
import matplotlib.pyplot as plt

N = 256
img = cv.imread("lena_full.jpg")
img2 = cv.Mat()
cv.cvtColor(img, img2, cv.CV_BGR2GRAY)
img = cv.Mat()
cv.resize(img2, img, cv.Size(N, N))

fimg = fft.fft2(img[:])
mag_img = np.log10(np.abs(fimg))
shift_mag_img = fft.fftshift(mag_img)

rects = [(80, 125, 85, 130), (90, 90, 95, 95), (150, 10, 250, 250),
         (110, 110, 146, 146)]

filtered_results = []
for i, (x0, y0, x1, y1) in enumerate(rects):
    mask = np.zeros((N, N), dtype=np.bool)
    mask[x0:x1 + 1, y0:y1 + 1] = True
    mask[N - x1:N - x0 + 1, N - y1:N - y0 + 1] = True
    mask = fft.fftshift(mask)
    fimg2 = fimg * mask
    filtered_img = fft.ifft2(fimg2).real
    filtered_results.append(filtered_img)

### 绘图部分 ###