像素重叠创建黑色斑点 - 蟒蛇

时间:2017-09-25 03:33:20

标签: python numpy image-processing

我正在尝试在PIV中创建图像中的粒子(然后替换,旋转,剪切图像)。我使用以下代码来获取我的粒子。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 09:47:24 2017

@author: arun
Program to create synthetic particles.
Makeparticles : Version 1

updates : 1) change particle diameter variation
          2) Image transformations using transformation matrix
          3) Time saved = 15 seconds faster
"""
import cv2
import numpy as np
import time
from PIL import Image
import mahotas
from affine import Affine
#from skimage import io
#from skimage import transform as tf
#import matplotlib.pyplot as plt
#import math
#import matplotlib as mpl
#import matplotlib.pyplot as plt
#import trackpy as tp
#import pims

"""---------------------make particles--------------------------------"""
class Particles(object):

    def __init__(self,n,extra,w,h,r1,r2):

        self.x = np.random.uniform(low=0.0, high=1680.0, size=n)
        self.y = np.random.uniform(low=0.0, high=1424.0, size=n)
        self.rad=np.random.uniform(low=r1, high=r2, size=n)
        self.n=n
        self.extra=extra
        self.w=w
        self.h=h

#    Initial location of particles. We use floating point ( not integer) 
#    to specify random location      

    def randomloc(self) :  


        for i in range(0,n) :
            frame.add_spot((self.x[i], self.y[i]), 255, self.rad[i])

        return self.x,self.y    

    def displacement(self,xdisp=20,ydisp=0):  
        img = cv2.imread('initial_image.jpg',0)
        rows,cols = img.shape
        M = np.float32([[1,0,xdisp],[0,1,ydisp]])
        dst = cv2.warpAffine(img,M,(cols,rows))
        cropped = dst[self.extra:self.w+self.extra, \
                      self.extra:self.h+self.extra]
        return cropped
        #plt.imshow(dst)


    def rotate(self, ox,oy,angle):    
        img = cv2.imread('initial_image.jpg',0)
        rows,cols = img.shape
        M = cv2.getRotationMatrix2D((ox,oy),angle,1) 
        # the format is cv2.getRotationMatrix2D(center, angle, scale) 
        dst = cv2.warpAffine(img,M,(cols,rows),flags=cv2.INTER_LANCZOS4)
#        area = (200, 200,1480,1224)
#        cropped_img = dst.crop(area)
        cropped = dst[200:1480, 200:1224]

        return cropped
    def shear2(self,anglex,angley):      
        img = cv2.imread('initial_image.jpg',0)
        rows,cols = img.shape
        M =  Affine.shear(anglex, angley)
        M=M[0:6]
        a = np.array(M).reshape(2,3)
        dst = cv2.warpAffine(img,a,(cols,rows),flags=cv2.INTER_LANCZOS4)
        cropped = dst[200:1480, 200:1224]    
        return cropped

#    
#    def shear0(self,angle):
#        image = io.imread("initial_image.jpg")
#
#        # Create Afine transform
#        afine_tf = tf.AffineTransform(shear=angle)
#        
#        # Apply transform to image data
#        modified = tf.warp(image, inverse_map=afine_tf)
#        
#        # Display the result
#        cropped = modified[200:1480, 200:1224]
#        #cropped_img.save('sheared_image.jpg')
#        return modified

#    def shear1(self,):
#        img = cv2.imread("initial_image.jpg")
#        rows,cols,ch = img.shape
#        
#        pts1 = np.float32([[50,50],[200,50],[50,200]])
#        pts2 = np.float32([[10,100],[200,50],[100,250]])
#        M = cv2.getAffineTransform(pts1,pts2)
#        dst = cv2.warpAffine(img,M,(cols,rows))




class SimulatedFrame(object):

    def __init__(self, shape, dtype=np.uint8):
        self.image = np.zeros(shape, dtype=dtype)
        self._saturation = np.iinfo(dtype).max
        self.shape = shape
        self.dtype =dtype
#""" A gaussian distribution of intensities is obtained. Eccentricity 
#    (ecc) means how much the particle is elongated . """

    def add_spot(self, pos, amplitude, r, ecc=0):
        "Add a Gaussian spot to the frame."
        x, y = np.meshgrid(*np.array(list(map(np.arange, self.shape))) \
                           - np.asarray(pos))
        spot = amplitude*np.exp(-((x/(1 - ecc))**2 + (y*(1 - ecc))**2)/\
                                (2*r**2)).T
        self.image += np.clip(spot, 0, self._saturation).astype\
                        (self.dtype)

    def save_frame(self, filename='initial_image1.jpg'):
        img = Image.fromarray(self.image.astype(np.uint8))
        #cropped = img[200:1480, 200:1224]
        img.save('initial_image.jpg')
        area = (200, 200,1224,1480)
        cropped = img.crop(area)
        cropped.save(filename)

#-------------------------------------------------------------------------
""" Definition of parameters
   This part is used to create an image with particles. This is to verify and 
   test the program that it works as intended An initial image at time T0, 
   with the particles having a circular and guassian distribution of their 
   intensities is made using the Makepart function definition. Then these 
   particles are displaced through translation, rotation and shear motions,
   and this image is used to compute the velocity and vorticity vectors later
   by cross correlation . 

   The variables used in this part are described as follows

   w =     width of the image
   h =     height of the image
   n =     Number of particles 
   r1 =     Radius of Particle in pixels: Lower limit
   r2 =     Radius of particle in pixels: Upper limit   
   xdisp = Displacement required in the x direction 
   ydisp = Displacement required in the y direction
   rotangle = Rotation requried in degrees (Anti-clockwise rotation)
   ox,oy = location of the point about which rotation occurs 
   shearx= shear angle in x direction.Positive value indicates bottom side 
           shift to right
   sheary= shear angle in y direction.Positive value indicates right side 
           shift to down
"""       

start1=time.time()
w=1280
h=1024   
n=500
r1 =3.0
r2= 5.0 
xdisp=20
ydisp=0
rotangle=1
ox=840
oy=712
shearx=1.0
sheary=0
extra=200  


"""creating an object for the class SimulatedFrame.
   Input - total window size, dtype of image
   Output- Black image of the desired pixel size
"""       
frame = SimulatedFrame((w+extra, h+extra), dtype=np.int)

#we send the number of particles to the class,
#so that we can make locations

coordinates=Particles(n,extra,w,h,r1,r2)        
x,y=coordinates.randomloc()
frame.save_frame()  

x1=coordinates.displacement(xdisp,ydisp)
mahotas.imsave('displaced.jpg', x1)


x2=coordinates.rotate(ox,oy,rotangle)
mahotas.imsave('rotated.jpg', x2)

x3=coordinates.shear2(shearx,sheary)
mahotas.imsave('sheared.jpg',x3)

print("--- %s seconds ---" % (time.time() - start1))

然而,在两个粒子重叠的地方,我得到了一个我想避免的黑点。我相信这是因为像素光强度计数器一旦达到255就会回到0.有没有办法避免这些黑点?

This is the image output

0 个答案:

没有答案